Python 如何根据 Pandas 数据框中的列表重新排序索引行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30009948/
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 reorder indexed rows based on a list in Pandas data frame
提问by neversaint
I have a data frame that looks like this:
我有一个如下所示的数据框:
company Amazon Apple Yahoo
name
A 0 130 0
C 173 0 0
Z 0 0 150
It was created using this code:
它是使用以下代码创建的:
import pandas as pd
df = pd.DataFrame({'name' : ['A', 'Z','C'],
'company' : ['Apple', 'Yahoo','Amazon'],
'height' : [130, 150,173]})
df = df.pivot(index="name", columns="company", values="height").fillna(0)
What I want to do is to sort the row (with index name
) according to a predefined list ["Z", "C", "A"]
. Resulting in this :
我想要做的是name
根据预定义的列表对行(带索引)进行排序["Z", "C", "A"]
。导致这个:
company Amazon Apple Yahoo
name
Z 0 0 150
C 173 0 0
A 0 130 0
How can I achieve that?
我怎样才能做到这一点?
采纳答案by Zero
You could set index on predefined order using reindex
like
您可以使用reindex
类似的方式按预定义的顺序设置索引
In [14]: df.reindex(["Z", "C", "A"])
Out[14]:
company Amazon Apple Yahoo
Z 0 0 150
C 173 0 0
A 0 130 0
However, if it's alphabetical order, you could use sort_index(ascending=False)
但是,如果按字母顺序排列,则可以使用 sort_index(ascending=False)
In [12]: df.sort_index(ascending=False)
Out[12]:
company Amazon Apple Yahoo
name
Z 0 0 150
C 173 0 0
A 0 130 0
Like pointed below, you need to assign it to some variable
就像下面指出的那样,您需要将其分配给某个变量
In [13]: df = df.sort_index(ascending=False)