社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python pandas根据多个条件选择行

ymilesz • 5 年前 • 1518 次点击  

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

输入数据是一个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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38265
 
1518 次点击  
文章 [ 2 ]  |  最新文章 5 年前
sacuL
Reply   •   1 楼
sacuL    6 年前

在你的 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
mad_
Reply   •   2 楼
mad_    6 年前

您应该能够通过下面的示例解决您的问题。你的语法在多种情况下是错误的

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