假设我有两个熊猫数据框:
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_df
Labels
match_df
source_df.Label
match_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和更有效的方法来实现这种行为?