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

pandas - set value on multiple columns conditionally

I have a set of columns that reflect components to another column. When that column is negative, I will need to zero it out. I need to also zero out all of the component columns. How do I do this?

filter_col = [col for col in t18_df if col.startswith('aum_')]
t18_df.loc[t18_df['AUM'] < 0] # these rows should have zeroed values only on filter_col
question from:https://stackoverflow.com/questions/65892091/set-value-on-multiple-columns-conditionally

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

1 Reply

0 votes
by (71.8m points)

You can just pass the filter_col into loc:

filter_col = [col for col in t18_df if col.startswith('aum_')]

# zero out filter_col
t18_df.loc[t18_df['AUM'] < 0, filter_col] = 0

# zero out AUM itself
t18_df.loc[t18_df['AUM'] < 0, 'AUM'] = 0
# also
# t18_df['AUM'] = t18_df['AUM'].clip(0)

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

...