Python Dataframe 多次合并时重复列

Python Dataframe Duplicated Columns while Merging multple times

我有一个主数据框和一个子数据框。我想将子数据框中的每一列合并到主数据框中,并以主数据框中的列作为参考。我已经成功地得到了我想要的答案,只是我看到了主数据框的重复列。以下是我预期的和现在的答案。

当前解决方案:

df = pd.DataFrame({'Ref':[1,2,3,4]})
df1 = pd.DataFrame({'A':[2,3],'Z':[1,2]})

df = [df.merge(df1[col_name],left_on='Ref',right_on=col_name,how='left') for col_name in df1.columns]
df = pd.concat(df,axis=1)
df = 
   Ref    A   Ref    Z
0    1  NaN     1  1.0
1    2  2.0     2  2.0
2    3  3.0     3  NaN
3    4  NaN     4  NaN

预期答案:

df = 
   Ref    A    Z
0    1  NaN  1.0
1    2  2.0  2.0
2    3  3.0  NaN
3    4  NaN  NaN

获取dataframe列表时设置'Ref' col作为索引怎么样? (并重置索引,以便您将 Ref 作为列返回)

df = pd.DataFrame({'Ref':[1,2,3,4]}) 
df1 = pd.DataFrame({'A':[2,3],'Z':[1,2]})


df = [df.merge(df1[col_name],left_on='Ref',right_on=col_name,how='left').set_index('Ref') for col_name in df1.columns]
df = pd.concat(df,axis=1)

df = df.reset_index()

        Ref  A   Z
        1   NaN 1.0
        2   2.0 2.0 
        3   3.0 NaN 
        4   NaN NaN

这是一个还原过程。而不是列表理解使用 for - 循环,甚至 reduce:

from functools import reduce

reduce(lambda x, y : x.merge(df1[y],left_on='Ref',right_on=y,how='left'), df1.columns, df)

   Ref    A    Z
0    1  NaN  1.0
1    2  2.0  2.0
2    3  3.0  NaN
3    4  NaN  NaN

以上类似:

for y in df1.columns:
    df = df.merge(df1[y],left_on='Ref',right_on=y,how='left')
df
 
   Ref    A    Z
0    1  NaN  1.0
1    2  2.0  2.0
2    3  3.0  NaN
3    4  NaN  NaN
   

更新

使用duplicated:

>>> df.loc[:, ~df.columns.duplicated()]
   Ref    A    Z
0    1  NaN  1.0
1    2  2.0  2.0
2    3  3.0  NaN
3    4  NaN  NaN

旧答案

您可以使用:

# Your code
...
df = pd.concat(df, axis=1)

# Use pop and insert to cleanup your dataframe
df.insert(0, 'Ref', df.pop('Ref').iloc[:, 0])

输出:

>>> df
   Ref    A    Z
0    1  NaN  1.0
1    2  2.0  2.0
2    3  3.0  NaN
3    4  NaN  NaN