如何在数据框中连接共享相同名称的列

时间:2018-03-22 14:57:18

标签: python pandas join duplicates

我是熊猫新手。我的df看起来像这样:

  A   A   A   B   B   B
a NaN NaN 2   NaN NaN 5
b NaN 1   NaN 9   NaN NaN
c 3   NaN     NaN 7   NaN

我怎样才能获得

  A   B 
a 2   5
b 1   9 
c 3   7

看起来合并,连接适用于多个数据帧。我也试过

df.groupby(by=[A,B], axis=1)

但得到了

ValueError: Grouper and axis must be same length

3 个答案:

答案 0 :(得分:3)

我认为您需要使用汇总功能指定第一级,例如summeanfirstlast ......:

import pandas as pd

df = df.groupby(level=0, axis=1).sum()
print (df)
     A    B
a  2.0  5.0
b  1.0  9.0
c  3.0  7.0

如果需要按名称过滤列,请使用子集:

df = df[['A','B']].groupby(level=0, axis=1).sum()

如果使用索引值:

df1 = df.T
print (df1)
     a    b    c
A  NaN  NaN  3.0
A  NaN  1.0  NaN
A  2.0  NaN  NaN
B  NaN  9.0  7.0
B  NaN  NaN  NaN
B  5.0  NaN  NaN

df = df1.groupby(level=0).sum()
#default parameter axis=0 should be omit above
#df = df1.groupby(level=0, axis=0).sum()
print (df)
     a    b    c
A  2.0  1.0  3.0
B  5.0  9.0  7.0

答案 1 :(得分:1)

也许使用first

df.groupby(df.columns,axis=1).first()
Out[35]: 
     A    B
a  2.0  5.0
b  1.0  9.0
c  3.0  7.0

答案 2 :(得分:0)

一种简洁的方法是使用numpy.isfinite列表理解:

import pandas as pd, numpy as np

arr = [list(filter(np.isfinite, x)) for x in df.values]

res = pd.DataFrame(arr, columns=['A', 'B'], index=['a', 'b', 'c'], dtype=int)

结果:

   A  B
a  2  5
b  1  9
c  3  7