使用Python熊猫根据多种条件选择行

时间:2018-10-22 16:16:04

标签: python pandas

嗨,我正在尝试找到满足多个用户输入的行,我希望结果返回一条与航班日期和目的地匹配的单行,始发机场为亚特兰大。如果他们输入其他任何内容,则会返回错误并退出。

输入数据是如下所示的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'作为目的地,理想的输出将仅返回第一行。

2 个答案:

答案 0 :(得分:0)

在您的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

答案 1 :(得分:0)

您应该可以使用以下示例解决问题。您的语法在多种情况下都是错误的

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