重新分配数据框的索引

时间:2020-01-04 17:48:31

标签: python pandas numpy dataframe matplotlib

我有以下数据框:

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

如您所见,数字从1-12 / 1-12两次列出,相反,我想将索引更改为1-24。问题是在绘制时会看到以下内容:

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

Plot

我希望看到一条从1到24的连续线。

3 个答案:

答案 0 :(得分:2)

esta2 = esta2.reset_index()将使您获得0-23。如果您需要1-24,则可以只esta2.index = np.arange(1, len(esta2) + 1)

答案 1 :(得分:1)

只需重新分配索引:

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

答案 2 :(得分:0)

非常简单:

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