如果组被排序,并且模式总是相同的(没有缺失值),则使用numpy重新塑造:
cols = ['Person', 'Place', 'Thing']
out = df.loc[::len(cols), ['Sample']].reset_index(drop=True)
out[cols] = df['Subject'].to_numpy().reshape(-1, len(cols))
对于更通用的方法,仅假设类别在一个组中总是以相同的顺序,标识每个组的位置:groupby.cumcount
和map
名称,然后pivot
:
order = ['Person', 'Place', 'Thing']
out = (df.assign(col=df.groupby('Sample').cumcount()
.map(dict(enumerate(order))))
.pivot(index='Sample', columns='col', values='Subject')
.reset_index().rename_axis(columns=None)
)
rename
的变种:
order = ['Person', 'Place', 'Thing']
out = (df.assign(col=df.groupby('Sample').cumcount())
.pivot(index='Sample', columns='col', values='Subject')
.rename(columns=dict(enumerate(order)))
.reset_index().rename_axis(columns=None)
)
输出:
Sample Person Place Thing
0 1-1 Janet Boston Hat
1 1-2 Chris Austin Scarf
最后,如果你真的想要"主题"一栏,insert
它:
out.insert(1, 'Subject', out['Person'])
print(out)
Sample Subject Person Place Thing
0 1-1 Janet Janet Boston Hat
1 1-2 Chris Chris Austin Scarf
timings
如果可以使用numpy方法,它对输入更严格,但速度更快: