Pandas:重新索引会使数据框变得无序

17

我在使用Pandas进行排序和重置索引时遇到了一些问题:

dfm = dfm.sort(['delt'],ascending=False)
dfm = dfm.reindex(index=range(1,len(dfm)))

我重新索引后,数据框返回的是未排序的。我的最终目标是获得一个排序的数据框,其索引号从1-->len(dfm),如果有更好的方法实现这一点,我也不介意。

谢谢!

2个回答

38

不要重新索引,只需更改实际索引:

dfm.index = range(1,len(dfm) + 1)

那不会改变顺序,只会改变索引。


1
继续补充Ryan的答案:df.index = df.index.sort_values() - kztd

8

我认为你可能误解了reindex的作用。其使用传递的索引来选择沿着所传递轴的值,然后在当前索引与传入索引不匹配的位置填充NaN。而你真正需要的是将索引设置为其他内容:

In [12]: df = DataFrame(randn(10, 2), columns=['a', 'delt'])

In [13]: df
Out[13]:
       a   delt
0  0.222 -0.964
1  0.038 -0.367
2  0.293  1.349
3  0.604 -0.855
4 -0.455 -0.594
5  0.795  0.013
6 -0.080 -0.235
7  0.671  1.405
8  0.436  0.415
9  0.840  1.174

In [14]: df.reindex(index=arange(1, len(df) + 1))
Out[14]:
        a   delt
1   0.038 -0.367
2   0.293  1.349
3   0.604 -0.855
4  -0.455 -0.594
5   0.795  0.013
6  -0.080 -0.235
7   0.671  1.405
8   0.436  0.415
9   0.840  1.174
10    NaN    NaN

In [16]: df.index = arange(1, len(df) + 1)

In [17]: df
Out[17]:
        a   delt
1   0.222 -0.964
2   0.038 -0.367
3   0.293  1.349
4   0.604 -0.855
5  -0.455 -0.594
6   0.795  0.013
7  -0.080 -0.235
8   0.671  1.405
9   0.436  0.415
10  0.840  1.174

请记住,如果您希望len(df)在索引中出现,您需要将终点加1,因为Python在构建范围时不包括终点。


7
和大多数关于“reindex”的回答一样,这再次说明了“reindex”这个方法名称对于它所执行的操作来说是多么糟糕的一个名称。 - BrenBarn
@BrenBarn 嗯,也许吧。你会怎么称呼它? - Phillip Cloud
@BrenBarn 我有一种感觉,使用set_index可能会变得更糟:S 很棘手。 - Andy Hayden
2
@PhillipCloud: 我会把它命名为 get,因为它所做的只是根据现有的索引值获取元素。reindex 暗示你正在为现有值设置一个新的索引。 - BrenBarn
1
Pandas的“reindex”函数类似于Excel的“VLOOKUP”。 - Robert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接