1

I am trying to extract information from a number of countries from a dataset I downloaded. I was able to figure out how to pull one country, but have had syntax errors trying to pull more than one in the same line. Here it is with the output:

ef=df1.loc[df1['countries'] == 'Hong Kong']

print(ef)
  year ISO_code  countries  ECONOMIC FREEDOM  rank  quartile  \
  2016      HKG  Hong Kong              8.97   1.0       1.0   
  2015      HKG  Hong Kong              8.97   1.0       1.0   
  2014      HKG  Hong Kong              9.00   1.0       1.0   
  2013      HKG  Hong Kong              8.96   1.0       1.0   
  2012      HKG  Hong Kong              8.96   1.0       1.0   

Can someone explain how I pull multiple countries in the same line of code? Also, am I able to output this information into a separate .csv file?

Thanks for your help.

Burhan Ali
  • 2,258
  • 1
  • 28
  • 38

3 Answers3

2

If you want to filter the dataframe based on multiple countries you can use Series.isin.

country_list = ['Hong Kong', 'US', 'Canada', 'India', 'Russia']
ef = df1[df1['countries'].isin(country_list)]
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
1

You can try this:

df1[(df1['countries'] == 'Hong Kong') | (df1['countries'] == 'USA')]
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
0

So you are really asking two different things.

  1. How do I slice a dataframe using two different criteria?
  2. How to I export a dataframe to a .csv

First you can have as many criteria as you want when you are slicing your dataframes just like @NYC Coder said

ef = df1[(df1["countries"] == "Hong Kong") | (df1["countries"] == "Taiwan")]

Once you've defined all of your dataframes you can start writing them to .csv files

ef.to_csv("ef.csv", index=False)