3 回答
TA贡献1804条经验 获得超7个赞
首先,我们需要熔化 df1,以便对每行都有一个观察值
然后,您可以使用outhero合并到从两列中获取键
df_melt = pd.melt(df1,var_name='client_id',value_name='total_tickets')
df3 = pd.merge(df_melt ,df2,on=['client_id'],how='outer')
#make sure dtypes are the same.
#df_melt ['client_id'] = df_melt ['client_id'].astype(int)
df3 = df3[["account_id", "client_id", "total_tickets"]].sort_values(
"account_id", ascending=False
)
print(df3)
account_id client_id total_tickets
3 4char 4 NaN
1 3char 5 40.0
0 2char 30 122.0
2 17char 100 13.0
4 16char 9 NaN
TA贡献1859条经验 获得超6个赞
merge是键,但您必须首先转置初始数据帧,并进行一些修饰性更改,例如重置其索引并提供相关的列名称:
转换可以是:
df1.rename({0: 'total_tickets'}).T.rename_axis('client_id').reset_index()
给:
client_index total_tickets
0 30 122
1 5 40
2 100 13
完成此操作后,合并是微不足道的:
result = df2.merge(df1.rename({0: 'total_tickets'}).T.rename_axis('client_id').reset_index(),
on='client_id', how='left')
按预期给予:
account_id client_id total_tickets
0 4char 4 NaN
1 3char 5 40.0
2 2char 30 122.0
3 16char 9 NaN
4 17char 100 13.0
添加回答
举报