Predictive Hacks

How to filter a Pandas Dataframe based on a list and its order.

import pandas as pd

df = pd.DataFrame({'country': ['Italy', 'Greece', 'Japan', 'Germany']})
countries_to_keep = ['Japan', 'Italy']
0    Italy
1   Greece
2    Japan
3  Germany

The usual way to filter the Dataframe is by using the ‘isin’ function:

0   Italy
2   Japan

Now, If we want to keep the order of the list we can do the following:

ind=[df.index[df['country']==i].tolist() for i in selected_countries]
flat_ind=[item for sublist in ind for item in sublist]

2   Japan
0   Italy

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s