2024-04-19 05:50:47 发布
网友
我有这样一个数据帧:
ID Type 0 a1 y 1 a1 y 2 a2 y 3 a2 n 4 a3 n
我想重新索引如下:
ID Subindex Type a1 1 y 2 y a2 1 y 2 n a3 1 n
熊猫有什么命令能做到这一点吗?非常感谢!你知道吗
要给每组中的项目编号,请使用cumcount:
cumcount
import pandas as pd df = pd.DataFrame({'ID': ['a1', 'a1', 'a2', 'a2', 'a3'], 'Type': ['y', 'y', 'y', 'n', 'n']}) df['Subindex'] = df.groupby('ID').cumcount()+1 print(df)
收益率
ID Type Subindex 0 a1 y 1 1 a1 y 2 2 a2 y 1 3 a2 n 2 4 a3 n 1
要给每组中的项目编号,请使用
cumcount
:收益率
相关问题 更多 >
编程相关推荐