# Set limit
limit = 3
# Create Groups
groups = df.groupby('emp_id').cumcount() + 1
# Pivot to wide format with new columns
df = df.pivot_table(index='emp_id',
columns=groups[groups.le(limit)], # Limit groups
values='label')
# Update Column Labels
df.columns = df.columns.map('label_{:.0f}'.format)
# Reset Index
df = df.reset_index()
您可以按emp_id分组并使用cumcount:
现在,您应该有一个新的列,其名称用作轴。您只能保留所需的标签并执行透视
比如:
NB。我无法测试代码
类似的方法,我们可以使用^{} 枚举} 转到宽格式,但根据指定的限制筛选组。然后使用^{} 格式化列标题:
emp_id
,并使用^{df
:数据帧和导入:
相关问题 更多 >
编程相关推荐