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

python - Apply conditional function based on condition of column value

I have a data-frame where I would like to apply a simple function to every column except the first one. Take below as an example - although in reality my dataframe comprises hundreds of columns:

vals = [(0, 12, 0),
     (33, 0, 11),
     (44, 16, 21),
     (0, 32, 1),
     (66, 33, 27),
     (77, 0, 0)
     ]

df = pd.DataFrame(vals, columns=list('ABC'))

I would like to find a way I can instigate a rule whereby each value greater than 0 is replaced with a 1. Crucially, I do not want to apply this rule to the first column, which should remain as it is.

The closest I have got is a lambda function, which isn't working at all:

df = df.apply(lambda x: 1 if x > 0 else 0 if x.name != 'A' else x)
question from:https://stackoverflow.com/questions/66065864/apply-conditional-function-based-on-condition-of-column-value

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

1 Reply

0 votes
by (71.8m points)

When using the apply method, the applied function will either receive all the entire column (by default and if axis=0), or it will receive the entire row (axis=1). In your case, the lambda function is an element-wise function, this is why you need to use the applymap method.

df[['B', 'C']] = df[['B', 'C']].applymap(lambda x: 1 if x > 0 else 0)

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

...