序列的真值是二义的.使用a.empty, a.bool(), a.item(), a.any()或a.all() - n

  • 本文关键字:item all bool any empty 使用 python pandas
  • 更新时间 :
  • 英文 :


我试图添加一个新的列到一个嵌套逻辑的数据框,但我得到一个系列的错误"真值是模棱两可的。使用a.empty a.bool (), a.item (), a.any()或所有()"。我在网上找到的解决方案不适用于我的情况。

#original case statement in sql
,case when pd.min_compare_at_price is not null then pd.min_compare_at_price else
case when n.compare_price is null or n.compare_price = 0 then 
case when min(n.sales_price) is null then 
case when n.sales_price is null and n.compare_price is null then max(n.original_price) 
when n.sales_price is not null and n.compare_price is null then max(n.original_price)
else n.compare_price end
else min(n.sales_price) end
else n.compare_price end
end as current_std_price

在python中,列都在同一个数据框架'product_data'

product_data['current_std_price'] = np.where(not(pd.isna(product_data['min_compare_at_price'])),product_data['min_compare_at_price'],
np.where(pd.isna(product_data['compare_at_price']) | product_data['compare_at_price']==0,
np.where(pd.isna(product_data['min_price_prod']),
np.where(pd.isna(product_data['sales_price']) & pd.isna(product_data['compare_at_price']),product_data['original_price'],
np.where(not(pd.isna(product_data['sales_price'])) & pd.isna(product_data['compare_at_price']),product_data['original_price'],
product_data['compare_at_price']),
product_data['min_price_prod']))))

在排除故障时,我试着把它切成这样,但仍然有同样的错误:

product_data['current_std_price'] = np.where(not(pd.isna(product_data['min_compare_at_price'])),product_data['min_compare_at_price'],product_data['min_price_prod'])

我认为问题是与not,但我不确定如何解决它而不翻转逻辑,我想避免由于其复杂性。

感谢

你的问题是python中的逻辑运算符将匹配整个对象。您需要做的是一个元素智能逻辑操作。您可以使用numpy.logical_not(),或者,在布尔值数组之间的逻辑运算的特殊情况下,您可以使用位运算,在这种情况下是~运算符。

那么,下面的代码应该对你有用:

product_data['current_std_price'] = np.where(np.logical_not(pd.isna(product_data['min_compare_at_price'])),product_data['min_compare_at_price'],product_data['min_price_prod'])

product_data['current_std_price'] = np.where(~(pd.isna(product_data['min_compare_at_price'])),product_data['min_compare_at_price'],product_data['min_price_prod'])

相关内容

最新更新