而不是例如使用 group_by 计算总和 我想连接同一组中的所有行。下面的代码应该只组合/连接行,而不是 sum() 。如果每组有 5 行,则新数据框的列数将是 5 倍(每列 x 5)
例子:
这是我现在拥有的数据框。
Index Pool B C D E
70 Pool1 8.717402 7.873173 16.029238 8.533174
71 Pool1 7.376365 6.228181 9.272679 7.498993
72 Pool2 8.854857 10.340896 9.218947 8.670379
73 Pool2 11.509130 8.571492 19.363829 14.605199
74 Pool3 14.780578 7.405982 9.279374 13.551686
75 Pool3 7.448860 11.952275 8.239564 12.264440
我想要这样的:
Index Pool B1 C1 D1 E1 B2 C2 D2 E2
70 Pool1 8.717402 7.873173 16.029238 8.533174 7.376365 6.228181 9.272679 7.498993
71 Pool2 8.854857 10.340896 9.218947 8.670379 11.509130 8.571492 19.363829 14.605199
72 Pool3 14.780578 7.405982 9.279374 13.551686 7.448860 11.952275 8.239564 12.264440
我会为您提供示例代码,但不知道。如果我只是对行进行求和,我会使用:
t.groupby(['pool']).sum()
但我不想合并行并保留列结构,我想将行与同一组连接起来。
你可以尝试:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'Pool': ['a', 'a', 'b', 'b', 'c'], 'B':[1, 2, 3, 4, 5], 'C':[1,2,3,4,5]})
gd = df1.groupby('Pool')
def comb2(x):
rslt = dict()
for col in x.columns:
rslt[col]=x[col].tolist()
return pd.Series(rslt)
rslt = gd.apply(comb2)
rslt = rslt.drop('Pool', axis=1)
finaldf = pd.DataFrame()
for col in rslt.columns:
tempdf = rslt[col].apply(lambda x: pd.Series(x))
tempdf.columns = [col+str(i+1) for i in range(len(tempdf.columns))]
finaldf = pd.concat([finaldf, tempdf],axis=1)
print(finaldf)
Output:
B1 B2 C1 C2
Pool
a 1 2 1 2
b 3 4 3 4
c 5 NaN 5 NaN
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)