如果要对df进行排序,只需对索引或数据进行排序,然后直接将其分配给df的索引,而不是尝试将df作为arg传递,因为这会产生一个空列表:
In [7]:df.index = natsorted(a)df.indexOut[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))dfOut[13]: 00hr 0128hr 172hr 248hr 396hr 4In [14]:df = df*2dfOut[14]: 00hr 0128hr 272hr 448hr 696hr 8In [15]:df.reindex(index=natsorted(df.index))Out[15]: 00hr 048hr 672hr 496hr 8128hr 2
请注意,您必须将结果分配给
reindex新的df或它本身,它不接受
inplace参数。



