水平比较两个数据框并为差异插入空白行

Horizontally compare two dataframes and inset blank rows for differences

水平比较两个数据帧并插入空白行以查找差异。 我需要在没有 id 值的第二个数据框中查看空白行

df1 =

user    id  Amount
John    1   1000
Tom     2   2000
Tom     2   3000
Claire  3   4000
Mary    4   5000
 
df2 = 

user    id  Amount
John    1   1000
Tom     2   2000
Claire  3   4000
Mary    4   5000

为了水平比较我正在使用

pd.concat([df1, df2], 
                    axis=1,


Result=

user    id  Amount      user    id  Amount
John    1   1000        John    1   1000
Tom     2   2000        Tom     2   2000
Tom     2   3000        Claire  3   4000
Claire  3   4000        Mary    4   5000
Mary    4   5000                

我期望发生的事情:

user    id  Amount      user    id  Amount
John    1   1000        John    1   1000
Tom     2   2000        Tom     2   2000
Tom     2   3000                
Claire  3   4000        Claire  3   4000
Mary    4   5000        Mary    4   5000


您需要使用 merge() 进行连接(使用列中的值)。此外,您需要 rename() RHS 中的列并在 right_on= param

中使用相同的名称
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

这对我有用。

首先我创建了一个数据框来查找重复的 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)