2 回答

TA貢獻1869條經(jīng)驗 獲得超4個贊
也許您可以嘗試groupby以下操作ngroup():
#Generating df from above
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'])
# applying reset index and ngroup
df.reset_index(inplace=True)
df['Entry Number'] = df.groupby(['Day','Person']).ngroup() +1
df
結(jié)果:
Day Person Exercise Entry Number
0 1 Joe Curls 1
1 1 Joe Squats 1
2 1 Sandy Sprints 2
3 1 Sandy Bench 2
4 2 Joe Curls 3
5 2 Sandy Squats 4
6 3 Bob Pushups 5

TA貢獻1155條經(jīng)驗 獲得超0個贊
另一種方法是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
添加回答
舉報