Python 如何按索引对 Pandas DataFrame 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22211737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a Pandas DataFrame by index?
提问by midtownguru
When there is an DataFrame like the following:
当有如下所示的 DataFrame 时:
import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])
How can I sort this dataframe by index with each combination of index and column value intact?
如何在索引和列值的每个组合完好无损的情况下按索引对该数据框进行排序?
采纳答案by Paul H
Dataframes have a sort_indexmethod which returns a copy by default. Pass inplace=Trueto operate in place.
数据帧有一个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())
Gives me:
给我:
A
1 4
29 2
100 1
150 5
234 3
回答by fantabolous
Slightly more compact:
稍微紧凑一点:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
笔记:
sorthas been deprecated, replaced bysort_indexfor this scenario- preferable not to use
inplaceas it is usually harder to read and prevents chaining. See explanation in answer here: Pandas: peculiar performance drop for inplace rename after dropna
sort已被弃用,替换为sort_index用于此场景- 最好不要使用,
inplace因为它通常更难阅读并防止链接。在此处查看答案中的解释: Pandas:在 dropna 之后就地重命名的特殊性能下降

