python - Series 的真值是模棱两可的
问题描述
当我运行以下函数时,我得到一个系列的真值是模棱两可的错误。环顾网络,它看起来应该可以工作。有什么我想念的吗?我也对如何使用循环中的两列使用列表理解来做到这一点很感兴趣。
我试过使用 and 和 & 得到一些东西。我尝试放置 .any() 但它只使用第一个语句。我查看了 np.where 但我需要它与 3 if 语句一起使用,但我没有运气。
我看到其他人问过这个问题,我再次问的原因是我的代码与pandas 数据框中的多个 if else 条件的答案相同,并派生多个列。
def before_after(df,col1, col2):
if ((df[col1] >= 0) and (df[col2] >= 0)):
return (((df[col2]-df[col1])/df[col1])*100)
elif ((df[col1] < 0) and (df[col2] > 0)):
return (((df[col2]-df[col1])/(df[col1].abs()))*100)
elif ((df[col1] < 0) and (df[col2] < 0)):
return (((df[col2]-df[col1])/df[col1])*100)
错误是:
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
解决方案
您可以使用numpy.select
链式的第一个和第三个条件,|
按位OR
,因为相同的返回,如果没有条件匹配,也会返回一些默认值,例如NaN
:
def before_after(df,col1, col2):
m1 = (df[col1] >= 0) & (df[col2] >= 0)
m2 = (df[col1] < 0) & (df[col2] > 0)
m3 = (df[col1] < 0) & (df[col2] < 0)
s1 = ((df[col2]-df[col1])/df[col1])*100
s2 = ((df[col2]-df[col1])/(df[col1].abs()))*100
return np.select([m1 | m3, m2], [s1, s2], default=np.nan)
推荐阅读
- javascript - 如何在加载此 React 组件时触发此功能,而不是需要单击按钮?
- node.js - 任何想法/帮助如何让“npm start”工作
- jsf - 如何从命令更新progressBar
- r - 如何重新排序这个数据框?
- php - PHP:组合数组然后排序
- pandas - 从 MongoDB 字典到 Dataframe 映射
- php - 带有特殊字符的 Jquery 数据表编辑器 Where 子句
- angular - 我应该使用 Observable 来检测正在设置的值吗?
- liferay - Freemarker:将网页内容转换为 Json 对象
- python - Postgres 获取所有没有空值的列