如何简化pivot在pandas中的使用?
我有一个数据框,如下所示:如何简化pivot在pandas中的使用?,pandas,pivot-table,Pandas,Pivot Table,我有一个数据框,如下所示: Age Sex Score 18 M 25 20 F 30 19 M 22 18 M 30 20 F 27 18 M 28 我想得到以下信息: Age Sex Score0 Score1 Score2 18 M 25 30 28 20 F 30 27 -1 19 M 22 -1 -1 我的步骤是: def func(x): x['score'] = ['S
Age Sex Score
18 M 25
20 F 30
19 M 22
18 M 30
20 F 27
18 M 28
我想得到以下信息:
Age Sex Score0 Score1 Score2
18 M 25 30 28
20 F 30 27 -1
19 M 22 -1 -1
我的步骤是:
def func(x):
x['score'] = ['Score' + str(i) for i in range(len(x))]
return x
df['key'] = df['Sex'] + df['Age'].astype(str)
dg = df.groupby(['Age', 'Sex']).apply(func)
dh =dg.pivot(index='key', columns = 'score', values = 'Score').reset_index().fillna(-1)
score key Score0 Score1 Score2
0 F20 30.0 27.0 -1.0
1 M18 25.0 30.0 28.0
2 M19 22.0 -1.0 -1.0
有没有更简单的方法
谢谢。您可以在两列上使用pivot_表并分配:
输出:
col Age Sex Score1 Score2 Score3
0 18 M 25 30 28
1 19 M 22 -1 -1
2 20 F 30 27 -1
您可以在两列上使用pivot_表并指定:
输出:
col Age Sex Score1 Score2 Score3
0 18 M 25 30 28
1 19 M 22 -1 -1
2 20 F 30 27 -1
您可以使用set_index和unstack来完成此操作
您可以使用set_index和unstack来完成此操作
运行:
运行:
写的答案几乎完全相同,除了我在分配中添加了前缀,这可能会导致更多的开销谢谢你,广宏。写的答案几乎完全相同,除了我在分配中添加了前缀,这可能会导致更多的开销谢谢你,广宏。谢谢你,瓦尔迪欧博。谢谢你,瓦尔迪欧博。
df.set_index([(df['Sex']+df['Age'].astype(str)).rename('key'),
'Score'+df.groupby(['Sex','Age']).cumcount().astype(str)])['Score']\
.unstack(fill_value=-1).reset_index()
key Score0 Score1 Score2
0 F20 30 27 -1
1 M18 25 30 28
2 M19 22 -1 -1
df.groupby(['Age', 'Sex']).Score.apply(
lambda grp: grp.reset_index(drop=True))\
.unstack().fillna(-1, downcast='infer').add_prefix('Score')