【问题标题】:Pandas ValueError: The truth value of a Series is ambiguous, when indexing dataframe [closed]Pandas ValueError:索引数据帧时,系列的真值不明确[关闭]
【发布时间】:2019-04-06 17:09:18
【问题描述】:
我正在尝试使用以下代码对我的数据框 outlier_locations 应用布尔索引:
outlier_locations = month[(month.pickup_longitude != 0 and month.pickup_latitude != 0) & ((month.pickup_longitude <= -74.15) or (month.pickup_latitude <= 40.5774)or \
(month.pickup_longitude >= -73.7004) or (month.pickup_latitude>= 40.9176))]
但是,我得到了错误(下面的完整回溯):
Series 的真值是模棱两可的
为什么会发生这种情况,我可以做些什么来解决它?
【问题讨论】:
标签:
python
python-3.x
pandas
dataframe
indexing
【解决方案1】:
将您的 and 和 or 分别更改为 & 和 |。
【解决方案2】:
对于 Pandas 系列的布尔索引,您需要分别对“and”/“or”条件使用 bitwise & / | 运算符。为了便于阅读,您还可以将掩码拆分为组件:
m1 = month[['pickup_longitude', 'pickup_latitude']].ne(0).all(1)
m2 = month['pickup_longitude'].le(-74.15)
m3 = month['pickup_latitude'].le(40.5774)
m4 = month['pickup_longitude'].ge(-73.7004)
m5 = month['pickup_latitude'].ge(40.9176)
outlier_locations = month[m1 & (m2 | m3 | m4 | m5)]