代码之家  ›  专栏  ›  技术社区  ›  daiyue

熊猫系列确定听写中不存在的键

  •  1
  • daiyue  · 技术社区  · 6 年前

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

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    你的代码在工作,如果dict中没有键 NaN 列中的S value .

    所以需要所有 currency 具有 之后 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