简体   繁体   English

带有 if 条件循环的 python 列表理解

[英]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.如果我想根据另一列值的条件更改一列的值,是否可以对 dataframe 使用列表理解。

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).假设 dataframe usage_time_df有两列anomalydevice_years ,如果我理解正确,当lower_level中的值未达到lower_outlier (我猜是浮点数)时,您希望将anomaly中的值设置为device_years The natural way to do that is:这样做的自然方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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