我完成了一个数据框日志记录练习,其中包含两列多索引:Day和Person。每天,每个人都记录自己进行了哪些锻炼(如果锻炼过)。我想添加另一列,该列按顺序计算进入此日志的条目,如下所示。因此,对于每一对独特的一天和每个人,加1。
Day Person Exercise EntryNumber
1 Joe Curls 1
1 Joe Squats 1
1 Sandy Sprints 2
1 Sandy Bench 2
2 Joe Curls 3
2 Sandy Squats 4
3 Bob Pushups 5
这是在上面的数据帧中生成代码的代码。
import pandas as pd
df = pd.DataFrame({'Day':[1,1,1,1,2,2,3],
'Person':['Joe','Joe','Sandy','Sandy','Joe','Sandy','Bob'],
'Exercise':['Curls','Squats','Sprints','Bench','Curls','Squats','Pushups']})
df = df.set_index(['Day','Person'])
我将如何创建EntryNumber列?我已经尝试了所有方式的groupby和cumcount,但尚未弄清楚。
谢谢!
另一种方法是factorize
通过索引而不必分组:
df['EntryNumber'] = df.index.factorize()[0]+1
#df = df.reset_index() -> if you want to reset theindex
print(df)
Exercise EntryNumber
Day Person
1 Joe Curls 1
Joe Squats 1
Sandy Sprints 2
Sandy Bench 2
2 Joe Curls 3
Sandy Squats 4
3 Bob Pushups 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句