Pandas ValueError:索引datafram时,序列的真值不明确

2024-04-23 23:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用以下代码对数据帧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))]

但是,我得到了错误(下面是完整的回溯):

The truth value of a Series is ambiguous

为什么会发生这种情况?我能做些什么来修复它?你知道吗

enter image description here


Tags: orandofthe数据代码value错误
2条回答

对于Pandas系列的布尔索引,需要分别对“and”/“or”条件使用逐位&/|运算符。为了便于阅读,您还可以将遮罩拆分为以下组件:

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)]

andor分别更改为&|。你知道吗

相关问题 更多 >