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
348 views
in Technique[技术] by (71.8m points)

python - return n smallest indexes by column using pandas

I have the following (simplified) dataframe:

df = pd.DataFrame({'X': [1, 2, 3, 4, 5,6,7,8,9,10],
'Y': [10,20,30,40,50,-10,-20,-30,-40,-50],
'Z': [20,18,16,14,12,10,8,6,4,2]},index=list('ABCDEFGHIJ'))

Which gives the following:

    X   Y   Z
A   1  10  20
B   2  20  18
C   3  30  16
D   4  40  14
E   5  50  12
F   6 -10  10
G   7 -20   8
H   8 -30   6
I   9 -40   4
J  10 -50   2

I want to create a new dataframe that returns the index of the n smallest values, by column.

Desired output (say, 3 smallest values):

   X  Y  Z
0  A  J  J
1  B  I  I
2  C  H  H

What is the best way to do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use apply with nsmallest:

n = 3
df.apply(lambda x: pd.Series(x.nsmallest(n).index))

#   X   Y   Z
#0  A   J   J
#1  B   I   I
#2  C   H   H

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

...