【发布时间】:2019-05-07 16:05:42
【问题描述】:
当有如下DataFrame时:
import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])
如何在索引和列值的每个组合完好无损的情况下按索引对该数据帧进行排序?
【问题讨论】:
当有如下DataFrame时:
import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])
如何在索引和列值的每个组合完好无损的情况下按索引对该数据帧进行排序?
【问题讨论】:
Dataframes 有一个 sort_index 方法默认返回一个副本。传inplace=True就地操作。
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
给我:
A
1 4
29 2
100 1
150 5
234 3
【讨论】:
inplace 不推荐:github.com/pandas-dev/pandas/issues/16529
稍微紧凑:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
注意:
sort 已被弃用,在这种情况下被 sort_index 取代inplace,因为它通常更难阅读并防止链接。在此处查看答案中的解释:
Pandas: peculiar performance drop for inplace rename after dropna
【讨论】:
.sort() docstring 说DEPRECATED: use DataFrame.sort_values()
.sort() 已被弃用。替换将是 .sort_index(),正如 Paul H 在他的回答中使用的那样,在这种情况下,我们的答案之间的唯一区别是我不使用 inplace=True。