0

假设我有两个熊猫数据框:

import pandas as pd
source_df = pd.DataFrame.from_dict({"Total": [315.59, 241.17, 165.87],          
                                    "Label": ["id|1234", "id|2345", "id|2333"]})
    Total    Label
0  315.59  id|1234
1  241.17  id|2345
2  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"]})
                      Labels
0           id|1234; id|4957
1                    id|7632
2           id|2345; id|9342
3  id|2333; id|8321; id|9001

我想用 中的值替换值,Label选择中的行。因此,所需的输出将是:source_dfLabelsmatch_dfsource_df.Labelmatch_df.Labels

    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

我目前这样做的方法依赖于 DataFrame 之间的成对比较 using iterrows,这是出了名的慢并且应该避免:

for 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和更有效的方法来实现这种行为?

4

1 回答 1

1

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

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
于 2020-03-11T07:09:20.173 回答