Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select a part of a dataframe according to a list?

I have the following dataframe:

      import pandas as pd

      df = pd.DataFrame({'Name': ['MEXICO', 'CANADA', 'CANADA', 'PORTUGAL', 'ESPANHA', 
                                  'BRASIL', 'BRASIL', 'MEXICO'],                   
                         'Column_two': [1,2,3,4,5,6,7,8]                  
                         })

      print(df)

      # Output:

                  Name      Column_two
                 MEXICO        1
                 CANADA        2
                 CANADA        3
                PORTUGAL       4
                 ESPANHA       5
                  BRASIL       6
                  BRASIL       7
                  MEXICO       8

And I have the following list with some cities located in America:

      list_americ = ['MEXICO', 'CANADA', 'BRASIL']

I would like to keep in the dataframe only the ‘Name’ of the countries that are in the list_americ. So I tried to do the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     for correct_name in list_americ:
          df['Name'] = df['Name'].apply(lambda x: correct_name if correct_name == df['Name'] 
                       else x)

This code is producing the following error:

      ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I would like the output to be:

                  Name      Column_two
                 MEXICO        1
                 CANADA        2
                 CANADA        3
                  BRASIL       6
                  BRASIL       7
                  MEXICO       8

>Solution :

Use df.loc:

df.loc[df['Name'].isin(list_americ)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading