【问题标题】:how to map and concat value two data frame python如何将值映射和连接到数据框python
【发布时间】:2021-11-07 12:28:08
【问题描述】:

一个数据框作为

first = pd.DataFrame({'Code': [1,2,3,4],'Value': ['Apple','Ornage','Bannana', 'Graps']})

另一个数据框是

second= pd.DataFrame({'Code': ['1','2','1','2,4','3'],'Product id': ['A','B','C', 'D','E']})

我要求将代码替换为 python 编码中第三个表列 'Required field' 中的值。作为数据框

third= pd.DataFrame({'Code': ['1','2','1','2,4','3'],'Product id': ['A','B','C', 'D','E'],'Required Field':['Apple(1)','Orange(2)','Apple(1)','Orange(2),Graps(4)','Bannana(3)']})

【问题讨论】:

  • 请不要发布您的数据图像。将所需信息作为文本(格式正确,以便我们复制粘贴)
  • 请参阅修改为插入数据框代码。

标签: python pandas dictionary replace


【解决方案1】:
>>> df1=pd.DataFrame({"code": [1,2,3,4], "value": ["apple", "orange", "banana", "grapes"]})
>>> df1
   code   value
0     1   apple
1     2  orange
2     3  banana
3     4  grapes


>>> df2=pd.DataFrame({"id":['A','B','C','D','E'], "code": ["1","2","1","2,4","3"]})
>>> df2
  id code
0  A    1
1  B    2
2  C    1
3  D  2,4
4  E    3

将字符串转换为列出并映射来自其他数据帧的值:

>>> df2['code']=df2['code'].str.split(',').apply(lambda x: df1.set_index('code').loc[[int(i) for i in x]].value.tolist())
>>> df2
  id              code
0  A           [apple]
1  B          [orange]
2  C           [apple]
3  D  [orange, grapes]
4  E          [banana]

【讨论】:

    【解决方案2】:

    试试:

    second["Code"] = second["Code"].str.split(",")
    second = second.explode("Code")
    
    first["Code"] = first["Code"].astype(str)
    second["Code"] = second["Code"].astype(str)
    third = pd.merge(first, second, on="Code")
    
    third["Value"] = third.apply(lambda x: f"{x['Value']}({x['Code']})", axis=1)
    
    print(
        third.groupby("Product id", as_index=False)
        .agg({"Code": ",".join, "Value": ",".join})
        .rename(columns={"Value": "Required Field"})
    )
    

    打印:

      Product id Code      Required Field
    0          A    1            Apple(1)
    1          B    2           Orange(2)
    2          C    1            Apple(1)
    3          D  2,4  Orange(2),Graps(4)
    4          E    3          Bannana(3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 2019-03-16
      • 2020-08-26
      • 2016-06-04
      • 1970-01-01
      • 2018-10-10
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多