我有一个数据框如下:
df = pd.DataFrame({'year': [2010, 2011, 2012, 2015,2016,2017],
'sales': [10, 12, 13, 9, 11,7],
'Groups': ['AA', 'BB', 'AA', 'AA', 'CC', 'CC']})
我想做的是用整数索引值映射“组”列,以便为相同的组成员分配相同的索引号。像这样:
Index year sales Groups
1 2010 10 AA
2 2011 12 BB
1 2012 13 AA
1 2015 9 AA
3 2016 11 CC
3 2017 7 CC
我正在考虑使用 set_index,但不确定这是否是正确的方法。
我想做的是用索引值映射“组”列,以便为相同的组成员分配相同的索引号。像这样:
Index year sales Groups
1 2010 10 AA
2 2011 12 BB
1 2012 13 AA
1 2015 9 AA
3 2016 11 CC
3 2017 7 CC
感谢您的帮助。
最佳答案
使用ngroup
df.index=df.groupby('Groups').ngroup()+1
或者factorize
和cat.codes
df.index=pd.factorize(df.Groups)[0]+1
df.index=df.Groups.astype('category').cat.codes+1
关于python - 如何替换数据框中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913077/