【问题标题】:pandas match dict 'else'熊猫匹配字典'else'
【发布时间】:2017-06-03 18:47:32
【问题描述】:

我有一个问题:

import pandas

new_dict={
    'a':1,
    'b':2,
    'else':4
}
df=pandas.DataFrame([['new1','a'],['new2','b'],['new3','c'],['new4','d'],['new5','b']],columns=['new','id'])

这样的df

    new id
0  new1  a
1  new2  b
2  new3  c
3  new4  d
4  new5  b

我想要的结果:

   new id
0  new1  1
1  new2  2
2  new3  4
3  new4  4
4  new5  2

我尝试将 dict 转换为数据框并使用合并方法。但 'else' 不匹配:

import pandas

new_dict={'newid':['a','b','else'],
      'idd':[1,2,4]}
df2=pandas.DataFrame(new_dict,columns=['newid','idd'])
df=pandas.DataFrame([['new1','a'],['new2','b'],['new3','c'],['new4','d'],['new5','b']],columns=['new','id'])

我尝试使用 pandas 合并方法来解决这个问题,但我不知道下一步该做什么。谢谢!

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    你可以使用map:

    df.id = df.id.map(new_dict).fillna(new_dict['else']).astype(int)
    print (df)
        new  id
    0  new1   1
    1  new2   2
    2  new3   4
    3  new4   4
    4  new5   2
    

    numpy.where 的另一个解决方案:

    df.id = np.where(df.id.isin(new_dict), df.id.map(new_dict), new_dict['else']).astype(int)
    print (df)
        new  id
    0  new1   1
    1  new2   2
    2  new3   4
    3  new4   4
    4  new5   2
    

    【讨论】:

      【解决方案2】:

      您也可以将map 与函数一起使用。
      我还使用您指定的字典,但通过 get 方法访问值,您可以在该方法中指定默认值。

      def new(x):
          new_dict = dict(a=1, b=2)
          return new_dict.get(x, 4)
      
      df=pd.DataFrame([
          ['new1','a'],['new2','b'],
          ['new3','c'],['new4','d'],
          ['new5','b']],
          columns=['new','id'])
      
      
      df.id = df.id.map(new)
      
      print(df)
      
          new  id
      0  new1   1
      1  new2   2
      2  new3   4
      3  new4   4
      4  new5   2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        • 2017-07-31
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        相关资源
        最近更新 更多