0]] &-6ren">
gpt4 book ai didi

python - 在 Python 中从 Dataframe 中过滤多个条件

转载 作者:太空狗 更新时间:2023-10-30 02:02:33 28 4
gpt4 key购买 nike

我想使用多列的多个条件从数据框中过滤掉数据。我试过这样做:

arrival_delayed_weather = [[[flight_data_finalcopy["ArrDelay"] > 0]] & [[flight_data_finalcopy["WeatherDelay"]>0]]]
arrival_delayed_weather_filter = arrival_delayed_weather[["UniqueCarrier", "AirlineID"]]
print arrival_delayed_weather_filter

但是我收到此错误消息:

TypeError: unsupported operand type(s) for &: 'list' and 'list'

我该如何解决?

提前致谢

最佳答案

你需要 () 而不是 []:

arrival_delayed_weather = (flight_data_finalcopy["ArrDelay"] > 0) & 
(flight_data_finalcopy["WeatherDelay"]>0)

但似乎您需要 ix 来通过 mask 选择列 UniqueCarrierAirlineID - boolean indexing 有点修改:

mask = (flight_data_finalcopy["ArrDelay"] > 0) & 
(flight_data_finalcopy["WeatherDelay"]>0)
arrival_delayed_weather_filter=flight_data_finalcopy.ix[mask, ["UniqueCarrier","AirlineID"]]

示例:

flight_data_finalcopy = pd.DataFrame({'ArrDelay':[0,2,3],
'WeatherDelay':[0,0,6],
'UniqueCarrier':['s','a','w'],
'AirlineID':[1515,3546,5456]})

print (flight_data_finalcopy)
AirlineID ArrDelay UniqueCarrier WeatherDelay
0 1515 0 s 0
1 3546 2 a 0
2 5456 3 w 6

mask = (flight_data_finalcopy["ArrDelay"] > 0) & (flight_data_finalcopy["WeatherDelay"]>0)
print (mask)
0 False
1 False
2 True
dtype: bool

arrival_delayed_weather_filter=flight_data_finalcopy.ix[mask, ["UniqueCarrier","AirlineID"]]
print (arrival_delayed_weather_filter)
UniqueCarrier AirlineID
2 w 5456

关于python - 在 Python 中从 Dataframe 中过滤多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40510820/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com