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

python - pandas mask change value where condition true and false

I have a matrix of values. I want to rank the values in the columns and then set top ranked values to 1 and others to zero.

I have tried to do this using nlargest, head but the only solution I can figure out is to apply mask twice.

My solution is below, but is there a smarter way to do this?

many thanks

John

import pandas as pd
df = pd.DataFrame([(1, 2, 3),
                   (4, 5, 6),
                   (7, 8, 9),
                   (11, 21, 31),
                   (41, 51, 31),
                   (71, 51, 61),
                   (71, 81, 91)],
                  columns=('value_1','value_2','value_3'))

value_1 value_2 value_3
0 1 2 3
1 4 5 6
2 7 8 9
3 11 21 31
4 41 51 31
5 71 51 61
6 71 81 91

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

1 Reply

0 votes
by (71.8m points)

Try creating the boolean values and then use astype

(~(df.rank(ascending=False, axis=0, method='min') > N)).astype(int)

   value_1  value_2  value_3
0        0        0        0
1        0        0        0
2        0        0        0
3        0        0        1
4        1        1        1
5        1        1        1
6        1        1        1

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

...