Python Pandas Groupby/附加列 [英] Python Pandas Groupby/Append columns
本文介绍了Python Pandas Groupby/附加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的示例数据框:
Index Param1 Param2
A 1 2
A 3 4
B 1 3
B 4 Nan
C 2 4
我想得到的是:
Index Param1 Param2 Param3 Param4
A 1 2 3 4
B 1 3 4
C 2 4
使用熊猫来实现这一目标的最佳方法是什么?预先感谢您的帮助.
What would be the best way to achieve it using pandas? Thanks in advance for your help.
推荐答案
您可以使用 取消堆叠
:
You can use groupby
with unstack
:
def f(x):
return (pd.DataFrame(np.sort(x.values.ravel())))
df = df.groupby('Index')['Param1','Param2'].apply(f).unstack()
df.columns = df.columns.droplevel(0)
print (df)
0 1 2 3
Index
A 1 2 3 4
B 1 3 4 Nan
C 2 4 None None
因为如果使用 Series
get:
because if use Series
get:
TypeError:Series.name必须是可哈希的类型
TypeError: Series.name must be a hashable type
使用 的另一种解决方案>累积
:
df = df.set_index('Index').stack().reset_index(name='vals')
df['g'] = 'Param' + df.groupby('Index').cumcount().add(1).astype(str)
df = df.pivot(index='Index', columns='g', values='vals')
print (df)
g Param1 Param2 Param3 Param4
Index
A 1.0 2.0 3.0 4.0
B 1.0 3.0 4.0 NaN
C 2.0 4.0 NaN NaN
这篇关于Python Pandas Groupby/附加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文