简体   繁体   English

根据配对条件过滤大熊猫

[英]Filter pandas based on paired conditions

I'm having trouble to to filter a dataframe using the result of groupby condition. 我无法使用groupby条件的结果过滤数据帧。 I already tried to use an mask with isin() but it doesn't return only the paired conditions. 我已经尝试使用带有isin()的掩码,但它不会仅返回配对条件。

Suppose i have a dataset like this below: 假设我有一个如下所示的数据集:

    Dest    Origin  DepDelay
0   TPA     IAD     8.0
1   TPA     IAD     19.0
2   BWI     IND     8.0
4   BWI     IND     34.0
5   JAX     IND     25.0
6   LAS     IND     67.0
8   MCI     IND     2.0
10  MCO     IND     6.0
11  MCO     IND     94.0
... .... ... ...
7009710 ATL MSP     30.0

I wanna filter this using the result of groupby condition, where i got all top 5 routes. 我想用groupby条件的结果过滤这个,我得到了所有前5条路线。 To obtain the routes i used this code: 要获取我使用此代码的路线:

top_5_route = flights_df[flights_df['DepDelay'] > 0].groupby(['Origin', 'Dest'])['Dest'].size().nlargest(5).index.to_list()

top_5_route: top_5_route:

[('LAX', 'SFO'),
('DAL', 'HOU'),
('SFO', 'LAX'),
('ORD', 'LGA'),
('HOU', 'DAL')]

i wanna filter this dataframe based on this labels to get only the paired conditions for "Origin - Dest". 我想根据这个标签过滤这个数据帧,只得到“Origin - Dest”的配对条件。 For example, the new dataframe should contain only values where origin is LAX and the Dest is SFO and the others paired conditions. 例如,新数据帧应仅包含其中origin为LAX且Dest为SFO且其他配对条件的值。

If i use isin method the dataframe also will contain values LAX - SFO , LAX-HOU . 如果我使用isin方法,数据帧也将包含值LAX - SFOLAX-HOU That does not match the paired condition. 这与配对条件不匹配。

Thanks! 谢谢!

IIUC,你需要过滤与你的元组列表匹配的行,使用:

df.set_index(['Dest','Origin']).loc[top_5_route].reset_index()

You can create a new column called 'Route': 您可以创建一个名为“Route”的新列:

flights_df['Route'] = flights_df['Origin'] + '-' + flights_df['Dest']

And then group by route to get the top 5 delayed routes 然后按路线分组以获得前5条延迟路线

top_5_route = flights_df[flights_df['DepDelay'] > 0.0].groupby('Route').size().nlargest(5)

To filter the flights_df on these routes: 要过滤这些路线上的flights_df

flights_df[flights_df['Route'].isin(top_5_route.keys())]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM