替换Dataframe的某些索引值

时间:2017-04-11 09:16:28

标签: python indexing

我正在尝试更改数据帧的某个索引值。 数据框如下所示:

    start   stop    nested_in
0   2015-11-10 05:42:00+00:00   2015-11-10 07:22:00+00:00   -1.0
0   2015-11-10 05:42:00+00:00   2015-11-10 06:09:00+00:00   0.0
0   2015-11-10 06:21:00+00:00   2015-11-10 06:37:00+00:00   0.0
0   2015-11-10 06:42:00+00:00   2015-11-10 06:58:00+00:00   0.0
0   2015-11-10 17:00:00+00:00   2015-11-10 21:55:00+00:00   -1.0
0   2015-11-10 17:00:00+00:00   2015-11-10 17:45:00+00:00   4.0
0   2015-11-10 17:45:00+00:00   2015-11-10 18:01:00+00:00   4.0

以0为索引。

我想做这样的事情:

for i in range(0, df.size):
   df.index[i] = i

但是这给了我以下错误

TypeError: Index does not support mutable operations

我所能做的就是:

df.index = [i1, i2,... , i(df.size-1)]

所以对于这个例子:

df.index = [0,1,2,3,4,5,6]

我想要的输出是:

    start   stop    nested_in
0   2015-11-10 05:42:00+00:00   2015-11-10 07:22:00+00:00   -1.0
1   2015-11-10 05:42:00+00:00   2015-11-10 06:09:00+00:00   0.0
2   2015-11-10 06:21:00+00:00   2015-11-10 06:37:00+00:00   0.0
3   2015-11-10 06:42:00+00:00   2015-11-10 06:58:00+00:00   0.0
4   2015-11-10 17:00:00+00:00   2015-11-10 21:55:00+00:00   -1.0
5   2015-11-10 17:00:00+00:00   2015-11-10 17:45:00+00:00   4.0
6   2015-11-10 17:45:00+00:00   2015-11-10 18:01:00+00:00   4.0

我做了一些研究,但找不到简单的直接解决方案。

2 个答案:

答案 0 :(得分:2)

你可以选择:

df.reset_index(drop=True, inplace=True)

答案 1 :(得分:0)

试试这个 -

indices = range(df.shape[0]) # this can be anything as long as the length is same as that of the number of rows in the dataframe
df['indices'] = indices
df = df.set_index('indices')

print df.head()