python-3.x - 熊猫系列确定字典中不存在哪些键
问题描述
我有以下df
,
currency value
USD 1.0
EUR 2.0
RMB 3.0
我得到一个dict
包含汇率的,
rates = {'GBP': 0.76, 'USD': 1.0, 'CNY': 6.6}
当我做
df['value'].div(df['currency'].map(rates))
我怎么知道/得到哪个值currency
没有映射到rates
,比如KeyError
,我试过了
try:
df['amount'] = df.['value'].div(df['currency'].map(rates))
except KeyError as e:
print('Key {} does not exist in the exchange rates dictionary'.format(e.args[0]))
但没有抛出错误。我想知道该怎么做。
解决方案
您的代码正常工作,如果 dict 中没有键,则NaN
在 column 中获取 s value
。
所以需要所有currency
的NaN
s after map
:
a = df['value'].div(df['currency'].map(rates))
b = df.loc[a.isnull(), 'currency']
print (b)
1 EUR
2 RMB
Name: currency, dtype: object
推荐阅读
- php - img ng-src remember image path
- node.js - Know if express app is running as firebase cloud function
- c++ - C++ protobuf 无法反序列化消息
- node.js - 如何在运行 reactjs + meteor 应用程序时禁用控制台日志
- go - `type foo struct` 和 `type foo []struct` 之间的区别
- python - Python中的Timsort执行时间
- java - 如何从文件中删除绝对路径?
- c++ - 将指针转换为指向多维数组的指针
- ruby - Ruby:BigDecimal:同时是一个类和一个方法?
- html - 当我按下它们时,我的某些链接不会交互