如何匹配熊猫数据框中的列并打印特定的行值

时间:2019-01-17 20:52:35

标签: python pandas dataframe pattern-matching

我尝试在用户输入与行中一个值匹配的值之后匹配列中的行值。然后产生一些统计数据。例如,用户输入飞行起点州“ il”城市“芝加哥”目的地城市“ la”州“ CA”。您正在从芝加哥机场代码ORD飞往洛杉矶机场代码LAX。距离为2000英里,批准时间为3.25小时。从时间上最好的航空公司是美国航空(AA)。您从芝加哥IL机场代码ORD飞往LA机场代码LAX。距离是2000英里。使用AA航空公司,最快的飞行时间是2小时。

FlightDate  DayOfWeek   UniqueCarrier   Origin  OriginCityName  OriginState Dest    DestCityName    DestState   Route   DepTime ArrTime Delayed TaxiOut TaxiIn  DelayLength SchedDuration   ActualDuration  AirTime Distance
12/1/2017   Friday  B6  ATL Atlanta  GA BOS Boston  MA  ATL<-->BOS  948 1214    0   23  3   -26 165 146 120 946
12/1/2017   Friday  B6  ATL Atlanta  GA BOS Boston  MA  ATL<-->BOS  1208    1436    0   11  7   -26 166 148 130 946


OriginState = input('enter origin state ')
OriginCity = input('enter origin city ')
for i,r in df.iterrows():
    if r['OriginState'] == OriginState and r['OriginCityName'] == OriginCity:
        originplace = r['Origin']
    else:
        pass
DestState = input('enter destination state ')
DestCity = input('enter destination city ')
for index,row in df.iterrows():
    if row['DestState'] == DestState and row['DestCityName'] == DestCity:
        DestPlace = row['Dest']
    else:
        pass
print('You are flying from',OriginState,'airport code',originplace,'to',DestCity,'airport code',DestPlace,'.')

1 个答案:

答案 0 :(得分:0)

您可以使用以下方法获得从起点到目的地的所有航班:
df_custom= df[(df['OriginState'] == OriginState) & ( df['OriginCityName'] == OriginCity) & (df['DestState'] == DestState) & (df['DestCityName'] == DestCity)]

然后使用df_custom获得持续时间最短的最佳航班。