[英]Adding a new column to a Pandas DataFrame by comparing two columns to two similar columns in a different Dataframe
我想向 Pandas DataFrame 添加一個新列,方法是獲取兩列中的值並將它們與在不同 dataframe 中以相同順序出現的值進行比較。
例子:
first_names = pd.Series(['john','jack','jean','jose'])
last_names = pd.Series(['bob','steve','carl','anthony'])
names1 = pd.DataFrame({'firstname': first_names, 'lastname':last_names})
names2 = pd.DataFrame({'firstname': first_names,"lastname":['bob','steve','carl','joshua']})
firstname lastname
0 john bob
1 jack steve
2 jean carl
3 jose anthony
firstname lastname
0 john bob
1 jack steve
2 jean carl
3 jose joshua
我想將“真實”列添加到 names2,如果名字和最后一個組合在 names1 中,則用 True 填充,否則用 False 填充。
這是我的嘗試:
def verify(first,last):
if names1.loc[ (names1['firstname'].str.contains(first)) & (names1['lastname'].str.contains(last)) , ['firstname','lastname'] ].empty:
return False
else:
return True
names2['real'] = verify(names2['firstname'], names2['lastname']))
我得到了令人沮喪的錯誤: TypeError: 'Series' objects are mutable, thus they cannot be hashed
並且它似乎被拋出在 function verify內的以下行:
names1.loc[ (names1['firstname'].str.contains(first)) & (names1['lastname'].str.contains(last)), ['firstname','lastname'] ].empty:
盡管在直接值時調用 function 時它可以正常工作:
verify('jose','anthony')
返回True
這讓我認為這些值不是作為字符串傳遞的
如何將值正確傳遞給上述 function? 是否有更直接的方法來完成比較?
編輯:我忘了提到我的數據框的大小不匹配。 datafaname names2 的行數比 names1 多。 使用 names1 保存查找數據並充當檢查真實/虛假名字和姓氏組合的參考。
您可以使用兩個數據框之間的叉積構造"real"
列,然后合並回names1
:
tmp = names1.merge(names2, how="cross")
tmp["real"] = (tmp["firstname_x"] == tmp["firstname_y"]) & (
tmp["lastname_x"] == tmp["lastname_y"]
)
df_out = names1.merge(
tmp[tmp["real"] == True],
left_on=["firstname", "lastname"],
right_on=["firstname_x", "lastname_x"],
how="left",
).fillna(False)[["firstname", "lastname", "real"]]
print(df_out)
印刷:
firstname lastname real
0 john bob True
1 jack steve True
2 jean carl True
3 jose anthony False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.