自然排序Pandas DataFrame

发布于 2021-01-29 15:04:06

我有一个熊猫DataFrame,它的索引要自然排序。Natsort似乎不起作用。在构建DataFrame之前对索引进行排序似乎无济于事,因为我对DataFrame所做的操作似乎使过程中的排序变得混乱。关于如何自然使用索引的任何想法?

from natsort import natsorted
import pandas as pd

# An unsorted list of strings
a = ['0hr', '128hr', '72hr', '48hr', '96hr']
# Sorted incorrectly
b = sorted(a)
# Naturally Sorted 
c = natsorted(a)

# Use a as the index for a DataFrame
df = pd.DataFrame(index=a)
# Sorted Incorrectly
df2 = df.sort()
# Natsort doesn't seem to work
df3 = natsorted(df)

print(a)
print(b)
print(c)
print(df.index)
print(df2.index)
print(df3.index)
关注者
0
被浏览
77
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果要对df进行排序,只需对索引或数据进行排序,然后直接将其分配给df的索引,而不是尝试将df作为arg传递,因为这会产生一个空列表:

    In [7]:
    
    df.index = natsorted(a)
    df.index
    Out[7]:
    Index(['0hr', '48hr', '72hr', '96hr', '128hr'], dtype='object')
    

    请注意,df.index = natsorted(df.index)也可以

    如果将df作为arg传递,则会产生一个空列表,在这种情况下,因为df为空(没有列),否则它将返回排序后的列,而不是您想要的:

    In [10]:
    
    natsorted(df)
    Out[10]:
    []
    

    编辑

    如果要对索引进行排序,以便数据与索引一起重新排序,请使用reindex

    In [13]:
    
    df=pd.DataFrame(index=a, data=np.arange(5))
    df
    Out[13]:
           0
    0hr    0
    128hr  1
    72hr   2
    48hr   3
    96hr   4
    In [14]:
    
    df = df*2
    df
    Out[14]:
           0
    0hr    0
    128hr  2
    72hr   4
    48hr   6
    96hr   8
    In [15]:
    
    df.reindex(index=natsorted(df.index))
    Out[15]:
           0
    0hr    0
    48hr   6
    72hr   4
    96hr   8
    128hr  2
    

    请注意,您必须将结果分配给reindex新的df或它本身,它不接受inplace参数。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看