【问题标题】:Selecting rows based on multiple conditions using Python pandas使用 Python pandas 根据多个条件选择行
【发布时间】:2023-03-14 01:24:01
【问题描述】:

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

输入数据是一个 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 作为“日期”并输入“IAD”作为目的地,理想的输出只是返回第一行。

【问题讨论】:

  • 有什么问题?是不是没有按预期返回。抛出错误??

标签: python pandas


【解决方案1】:

您应该能够通过以下示例解决您的问题。你的语法在多个条件下都是错误的

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      相关资源
      最近更新 更多