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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:29:21  来源:igfitidea点击:

How to sort a Pandas DataFrame by index?

pythonpandas

提问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:

笔记: