gpt4 book ai didi

python - 如何替换数据框中的索引

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:23 25 4
gpt4 key购买 nike

我有一个数据框如下:

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

或者factorizecat.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com