简体   繁体   中英

python list comprehension with if condition looping

Is it possible to use list comprehension for a dataframe if I want to change one column's value based on the condition of another column's value.

The code I'm hoping to make work would be something like this:

return ['lower_level' for x in usage_time_df['anomaly'] if [y < lower_outlier for y in usage_time_df['device_years']]

Thanks!

I don't think what you want to do can be done in a list comprehension, and if it can, it will definitely not be efficient.

Assuming a dataframe usage_time_df with two columns, anomaly and device_years , if I understand correctly, you want to set the value in anomaly to lower_level when the value in device_years does not reach lower_outlier (which I guess is a float). The natural way to do that is:

usage_time_df.loc[usage_time_df['device_years'] < lower_outlier, 'anomaly'] = 'lower_level'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM