2 回答

TA贡献1811条经验 获得超4个赞
您需要使用merge()来进行连接(使用列中的值)。此外,您需要rename()RHS 中的列并在right_on=参数中使用相同的名称
df1 = pd.read_csv(io.StringIO("""user id Amount
John 1 1000
Tom 2 2000
Tom 2 3000
Claire 3 4000
Mary 4 5000"""), sep="\s\s+", engine="python")
df2 = pd.read_csv(io.StringIO("""user id Amount
John 1 1000
Tom 2 2000
Claire 3 4000
Mary 4 5000"""), sep="\s\s+", engine="python")
df2.rename(columns={c:f"{c}_right" for c in df2.columns})
dfm = df1.merge(df2.rename(columns={c:f"{c}_right" for c in df2.columns}),
left_on=[c for c in df1.columns],
right_on=[f"{c}_right" for c in df2.columns],
how="left")
print(dfm.to_string(index=False))
输出
user id Amount user_right id_right Amount_right
John 1 1000 John 1.0 1000.0
Tom 2 2000 Tom 2.0 2000.0
Tom 2 3000 NaN NaN NaN
Claire 3 4000 Claire 3.0 4000.0
Mary 4 5000 Mary 4.0 5000.0

TA贡献1817条经验 获得超6个赞
这对我有用。
首先,我创建了一个数据框来查找重复的 ID
duplicate = df1[df1['id'].duplicated()]
然后我查找了这个新的数据框以确定我需要哪些 ID 来插入一个空行
df2= df2.assign(result=df2['id'].isin(duplicate['id']).astype(int))
我创建了一个结果列来标识我需要插入空行的行
a = (df2['result'] == 1)
df3 = df2.copy() #make a copy because we want to be safe here
for i in df2.loc[a].index:
empty_row = pd.DataFrame([], index=[i]) #creating the empty data
j = i + 1 #just to get things easier to read
df3 = pd.concat([df3.ix[:i], empty_row, df3.ix[j:]], sort=False) #slicing the df
df3 = df3.reset_index(drop=True,) #reset the index
在 df3 上插入空行后,我使用 pd.concat 并排显示两个 dfs
df_all =pd.concat([df1, df3], axis=1, sort=False)
添加回答
举报