【问题标题】:create pandas column with new values based on values in other columns根据其他列中的值创建具有新值的 pandas 列
【发布时间】:2021-05-06 08:57:33
【问题描述】:

数据框一:

    id    value
-------------------------------
0   231   9243
1   392   81139
2   493   896546
3   879   31

数据框 b:

   id   description  colour
-------------------------------
0  231  football     brown
1  392  bat          white
2  556  chicken      yellow 
3  493  tennis ball  yellow
4  119  pig          pink
5  879  cricket ball red

我的问题是如何在数据框 a 中创建一个新列,根据与数据框 a 中的 id 列值的匹配来输入来自数据框 b 的描述?所以我最终得到:

    id    description    value    
-------------------------------
0   231   football        9243
1   392   bat             81139
2   493   tennis ball     896546
3   879   cricket ball    31

【问题讨论】:

    标签: python pandas multiple-columns


    【解决方案1】:

    您可以创建一个字典,用于从数据帧b 映射iddescription,然后在id 列上的数据帧a 上使用.map(),如下所示:

    b_dict = dict(zip(b['id'], b['description']))
    a['description'] = a['id'].map(b_dict).fillna('')
    

    结果:

    print(a)
    
        id   value   description
    0  231    9243      football
    1  392   81139           bat
    2  493  896546   tennis ball
    3  879      31  cricket ball
    

    【讨论】:

      【解决方案2】:

      通过left merge

      df1 = df1.merge(df2[['id','description']], on='id', how='left')
      

      输出

          id   value   description
      0  231    9243      football
      1  392   81139           bat
      2  493  896546   tennis_ball
      3  879      31  cricket_ball
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-24
        • 2020-08-18
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多