gpt4 book ai didi

python - 基于两列合并两个 Dataframe

转载 作者:行者123 更新时间:2023-12-01 06:36:06 24 4
gpt4 key购买 nike

我有两个数据帧:df1df_outdf1 看起来像这样

   phone_number1  phone_number2
1 123 123
2 345 0
3 678 678
4 912 912
5 555 666

df_out

    phone_number  address   name
1 123 add1 name1
2 777777 add2 name2
3 666 add3 name3
4 555 add4 name4

想做这样的东西

    phone_number  address   name    df1_phone_number1    df1_phone_number2
1 123 add1 name1 123 123
2 777777 add2 name2 None None
3 666 add3 name3 None 666
4 555 add4 name4 555 None

我尝试了此代码,但它不会保存与 phone_number2 匹配的数据

    mergedStuff3 = pd.concat([
pd.merge(df1, df_out, how='right', left_on=['phone_number1'], right_on = ['phone_number']),
pd.merge(df1, df_out, how='right', left_on=['phone_number2', 'phone_number1'], right_on = ['phone_number', 'phone_number'])

])

最佳答案

我认为你需要Series.where支票成员(member)资格 Series.isin :

m1 = df_out['phone_number'].isin(df1['phone_number1'])
m2 = df_out['phone_number'].isin(df1['phone_number2'])
df_out['df1_phone_number1'] = df_out['phone_number'].where(m1)
df_out['df1_phone_number2'] = df_out['phone_number'].where(m2)
print (df_out)
phone_number address name df1_phone_number1 df1_phone_number2
1 123 add1 name1 123.0 123.0
2 777777 add2 name2 NaN NaN
3 666 add3 name3 NaN 666.0
4 555 add4 name4 555.0 NaN

或者使用numpy.where :

m1 = df_out['phone_number'].isin(df1['phone_number1'])
m2 = df_out['phone_number'].isin(df1['phone_number2'])
df_out['df1_phone_number1'] = np.where(m1, df_out['phone_number'], None)
df_out['df1_phone_number2'] = np.where(m2, df_out['phone_number'], None)
print (df_out)
phone_number address name df1_phone_number1 df1_phone_number2
1 123 add1 name1 123 123
2 777777 add2 name2 None None
3 666 add3 name3 None 666
4 555 add4 name4 555 None

如果有更多列,则应更改解决方案:

for c in df1.columns:
m = df_out['phone_number'].isin(df1[c])
df_out[f'df1_{c}'] = np.where(m, df_out['phone_number'], None)

关于python - 基于两列合并两个 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59659247/

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