首页 > 解决方案 > 熊猫系列确定字典中不存在哪些键

问题描述

我有以下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]))

但没有抛出错误。我想知道该怎么做。

标签: python-3.xpandasdataframe

解决方案


您的代码正常工作,如果 dict 中没有键,则NaN在 column 中获取 s value

所以需要所有currencyNaNs 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

推荐阅读