使用Python基于多个条件选择行

2024-06-28 22:09:58 发布

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

嗨,我试图找到一个行,满足多个用户输入,我希望结果返回一个单一的行,匹配的航班日期和目的地,与始发机场是亚特兰大。如果他们输入了其他内容,它将返回一个错误并退出

输入数据是如下所示的CSV:

    FL_DATE ORIGIN  DEST    DEP_TIME
5/1/2017    ATL IAD 1442
5/1/2017    MCO EWR 932
5/1/2017    IAH MIA 1011
5/1/2017    EWR TPA 1646
5/1/2017    RSW EWR 1054
5/1/2017    IAD RDU 2216
5/1/2017    IAD BDL 1755
5/1/2017    EWR RSW 1055
5/1/2017    MCO EWR 744

我的当前代码:

import pandas as pd

df=pd.read_csv("flights.data.csv") #import data frame

input1 = input ('Enter your flight date in MM/DD/YYYY: ') #input flight date
try:
    date = str(input1) #flight date is a string
except:
    print('Invalid date') #error message if it isn't a string
    quit()

input2 = input('Enter your destination airport code: ') #input airport code
try:
    destination = str(input2) #destination is a string
except:
    print('Invalid destination airport code') #error message if it isn't a string
    quit()

df.loc[df['FL_DATE'] == date] & df[df['ORIGIN'] == 'ATL'] & df[df['DEST'] == destination]
#matches flight date, destination, and origin has to equal to GNV

理想的输出就是返回第一行,如果我输入5/1/2017作为'date','IAD'作为destination


Tags: dfinputdatestringcodeorigindestinationdest
2条回答

你应该可以用下面的例子来解决你的问题。你的语法在多个条件下都是错误的

import pandas as pd    
df=pd.DataFrame({'FL_DATE':['5/1/2017'],'ORIGIN':['ATL'],'DEST':['IAD'],'DEP_TIME':[1442]})
df.loc[(df['FL_DATE'] == '5/1/2017') & (df['ORIGIN'] == 'ATL') & (df['DEST'] == 'IAD')]

给予

DEP_TIME    DEST    FL_DATE     ORIGIN
1442        IAD     5/1/2017    ATL

你应该把代码改成这样

df.loc[(df['FL_DATE'] == date) & (df['ORIGIN'] == 'ATL') & (df['DEST'] == destination)]

loc语句中,需要固定括号并在条件之间添加括号:

df.loc[(df['FL_DATE'] == input1) & (df['ORIGIN'] == 'ATL') & (df['DEST'] == input2)]

然后它就起作用了:

>>> df.loc[(df['FL_DATE'] == date) & (df['ORIGIN'] == 'ATL') & (df['DEST'] == destination)]

    FL_DATE ORIGIN DEST  DEP_TIME
0  5/1/2017    ATL  IAD      1442

相关问题 更多 >