Reassign index of a dataframe

空扰寡人 提交于 2021-02-05 12:25:05

问题


I have the following dataframe:

Month
1    -0.075844
2    -0.089111
3     0.042705
4     0.002147
5    -0.010528
6     0.109443
7     0.198334
8     0.209830
9     0.075139
10   -0.062405
11   -0.211774
12   -0.109167
1    -0.075844
2    -0.089111
3     0.042705
4     0.002147
5    -0.010528
6     0.109443
7     0.198334
8     0.209830
9     0.075139
10   -0.062405
11   -0.211774
12   -0.109167
Name: Passengers, dtype: float64

As you can see numbers are listed twice from 1-12 / 1-12, instead, I would like to change the index to 1-24. The problem is that when plotting it I see the following:

plt.figure(figsize=(15,5))
plt.plot(esta2,color='orange')
plt.show()

I would like to see a continuous line from 1 to 24.


回答1:


esta2 = esta2.reset_index() will get you 0-23. If you need 1-24 then you could just do esta2.index = np.arange(1, len(esta2) + 1).




回答2:


quite simply :

df.index = [i for i in range(1,len(df.index)+1)]
df.index.name = 'Month'

print(df)
           Val
Month          
1     -0.075844
2     -0.089111
3      0.042705
4      0.002147
5     -0.010528
6      0.109443
7      0.198334
8      0.209830
9      0.075139
10    -0.062405
11    -0.211774
12    -0.109167
13    -0.075844
14    -0.089111
15     0.042705
16     0.002147
17    -0.010528
18     0.109443
19     0.198334
20     0.209830
21     0.075139
22    -0.062405
23    -0.211774
24    -0.109167



回答3:


Just reassign the index:

df.index = pd.Index(range(1, len(df) + 1), name='Month')


来源:https://stackoverflow.com/questions/59593321/reassign-index-of-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!