Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

python - How to reorder indexed rows based on a list in Pandas data frame

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 :

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

How can I achieve that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could set index on predefined order using reindex like

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)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...