gpt4 book ai didi

python - 用 pandas 下一列中存在的记录替换匹配的记录

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:29 24 4
gpt4 key购买 nike

我有两个数据框A,B

“A”数据框由1列组成(列名称:str1)

“B”数据框由2列组成(列名称:m2,m3)

我正在比较“A”的 str1 与“B”的 m2

我想要的是当“str1”与“m2”匹配时我希望“str1”被“m3”替换。以下是我的数据,

    data frame A.str1="gmaps","facebook","gmail","linkedin"
data frame B.m1 ="gmaps","oracle","gmail","intel"
data frame B.m2 ="Google","xyz","Google","nvidia"

我想要输出为

    data frame A.str1="Google","facebook","Google","linkedin"

因此,只要 A.str1 与 B.m1 匹配,A.str1 就会被 B.m2 替换提前致谢

最佳答案

我认为您需要创建助手Seriesreplace或使用map ,但它会为不匹配的列创建 NaN,因此这是必要的 fillnacombine_first :

df1 = pd.DataFrame({'str1': ["gmaps","facebook","gmail","linkedin"]})

df2 = pd.DataFrame({'m1': ["gmaps","oracle","gmail","intel"],
'm2': ["Google","xyz","Google","nvidia"]})

s = df2.set_index('m1')['m2']
print (s)
m1
gmaps Google
oracle xyz
gmail Google
intel nvidia
Name: m2, dtype: object

df1['str1'] = df1['str1'].replace(s)
#alternatives
#df1['str1'] = df1['str1'].map(s).fillna(df1['str1'])
#df1['str1'] = df1['str1'].map(s).combine_first(df1['str1'])
print (df1)

str1
0 Google
1 facebook
2 Google
3 linkedin

关于python - 用 pandas 下一列中存在的记录替换匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com