如何基于Pandas数据框中的列表对索引行进行重新排序 [英] How to reorder indexed rows based on a list in Pandas data frame

查看:304
本文介绍了如何基于Pandas数据框中的列表对索引行进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

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)

我想要做的是根据预定义的列表["Z", "C", "A"]对行(索引为name)进行排序.结果:

What I want to do is to sort the row (with index name) according to a predefined list ["Z", "C", "A"]. Resulting in this :

company  Amazon  Apple  Yahoo
name
Z             0      0    150
C           173      0      0
A             0    130      0

我该如何实现?

推荐答案

您可以使用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

但是,如果是字母顺序,则可以使用sort_index(ascending=False)

However, if it's alphabetical order, you could use 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)

这篇关于如何基于Pandas数据框中的列表对索引行进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆