为了账号安全,请及时绑定邮箱和手机立即绑定

基于列值作为子集的匹配数据帧

基于列值作为子集的匹配数据帧

呼唤远方 2022-08-25 15:53:17
假设我有两个熊猫数据帧:import pandas as pdsource_df = pd.DataFrame.from_dict({"Total": [315.59, 241.17, 165.87],                                              "Label": ["id|1234", "id|2345", "id|2333"]})    Total    Label0  315.59  id|12341  241.17  id|23452  165.87  id|2333和match_df = pd.DataFrame.from_dict(    {"Labels": ["id|1234; id|4957", "id|7632", "id|2345; id|9342", "id|2333; id|8321; id|9001"]})                      Labels0           id|1234; id|49571                    id|76322           id|2345; id|93423  id|2333; id|8321; id|9001我想替换使用 中的值中的值,选择 位于 中的行。因此,所需的输出将是:Labelsource_dfLabelsmatch_dfsource_df.Labelmatch_df.Labels    Total                      Label0  315.59           id|1234; id|49571  241.17           id|2345; id|93422  165.87  id|2333; id|8321; id|9001我目前这样做的方法依赖于 DataFrames using 之间的成对比较,这是出了名的慢,需要避免:iterrowsfor ii, row in source_df.iterrows():                                                for _, match_row in match_df.iterrows():                                            if row.Label in match_row.Labels:                                                   source_df.at[ii, "Label"] = match_row.Labels                                    break有没有一种更pythonic和更有效的方法来实现这种行为?
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

首先使用DataFrame.explode(pandas 0.25 +)由Series.str.split创建的列表,因此可以使用DataFrame.mergeLabels


df1 = match_df.assign(Label = match_df['Labels'].str.split('; ')).explode('Label')


df = source_df.merge(df1, on='Label')

print (df)

    Total    Label                     Labels

0  315.59  id|1234           id|1234; id|4957

1  241.17  id|2345           id|2345; id|9342

2  165.87  id|2333  id|2333; id|8321; id|9001

最后一列 :Label


df['Label'] = df.pop('Labels')

print (df)

    Total                      Label

0  315.59           id|1234; id|4957

1  241.17           id|2345; id|9342

2  165.87  id|2333; id|8321; id|9001

另一个具有Series.map和字典理解的解决方案:


d = {y: x for x in match_df['Labels'] for y in x.split('; ')}


source_df['Label'] = source_df['Label'].map(d)

print (source_df)

    Total                      Label

0  315.59           id|1234; id|4957

1  241.17           id|2345; id|9342

2  165.87  id|2333; id|8321; id|9001


查看完整回答
反对 回复 2022-08-25
  • 1 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号