如何将熊猫列放入具有自定义条件的行中?



我有这样的数据帧

DF1

A   B   C      SN
0  10  23  48  456123
1  15  45  98  789456
2  16  62  55  123789

DF2

A   B     C      SN
0  10  19  48.0  456123
1  15  45   NaN  789456
2  68  77  55.0  123789

我需要下面这样的东西

SN   123789  456123  789456
A_x    16    10    15
B_x    62    23    45
C_x    55    48    98
A_y    68    10    15
B_y    77    19    45
C_y    55    48     0

我尝试使用熊猫分组和枢轴,但没有按我想要的方式工作。有什么帮助吗?

您可以在下面执行以下操作。

output = pd.merge(df1,df2,on='SN').groupby(['SN']).sum().transpose()

输出:

SN   123789  456123  789456
A_x    16.0    10.0    15.0
B_x    62.0    23.0    45.0
C_x    55.0    48.0    98.0
A_y    68.0    10.0    15.0
B_y    77.0    19.0    45.0
C_y    55.0    48.0     0.0

稍后可以将类型从 float 更改为 int。

使用merge,必要时将0替换为fillnasort_index和 trne 转置set_indexT

#if need inner join
df3 = dfa.merge(df2,on='SN').fillna(0).sort_index().set_index('SN').T
#if need outer join
df3 = dfa.merge(df2,on='SN', how='outer').fillna(0).sort_index().set_index('SN').T
print (df3)
SN   456123  789456  123789
A_x    10.0    15.0    16.0
B_x    23.0    45.0    62.0
C_x    48.0    98.0    55.0
A_y    10.0    15.0    68.0
B_y    19.0    45.0    77.0
C_y    48.0     0.0    55.0

另一种与concat进行外连接的解决方案:

df3 = (pd.concat([df1.set_index('SN'), 
df2.set_index('SN')], axis=1, keys=('x', 'y')).T.fillna(0))
#flatten MultiIndex
df3.index = [f'{j}_{i}' for i, j in df3.index]
print (df3)
SN   456123  789456  123789
A_x    10.0    15.0    16.0
B_x    23.0    45.0    62.0
C_x    48.0    98.0    55.0
A_y    10.0    15.0    68.0
B_y    19.0    45.0    77.0
C_y    48.0     0.0    55.0

最新更新