lyngn
lyngn

Reputation: 13

Create multiple dataframe using for loop

Hi I have a dataset looking like this.

https://i.sstatic.net/cjYAW.png

I want to create mutiple dataframes using countryname_df = data.loc[data.location == 'country name'. This is an example result:

https://i.sstatic.net/UHkQ2.png

May I know if I can use loop for to create with this format:

     c_df = data.loc[data.location == c]

Upvotes: 0

Views: 1699

Answers (2)

BP34500
BP34500

Reputation: 178

the following example does what you want.

start by creating an empty list where you will store all the different dataframes.

Get a list of the unique countries.

import pandas as pd

data = {'country':['USA','USA','CANADA','CANADA','CANADA','SPAIN','SPAIN','PERU','PERU','PERU','PERU','PERU'],
        'col_1': [3, 2, 1, 0,235,2,5,7,9,7,14,346], 
        'col_2': ['a', 'b', 'c', 'd','v','asd','sg','sdg','ery','wqrew','asf','Ùùsd'],
        'col_3':[3234,52345,64534,65652,1234,435,346,7687,969,689689,79,2143]}
df = pd.DataFrame.from_dict(data)



list_of_df = []
unique_countries = set(list(df['country']))
for country in unique_countries:
  list_of_df.append(df.loc[df['country'] == country,:])

# this is the first dataframe of the list.
list_of_df[0]

Upvotes: 1

roadrunner66
roadrunner66

Reputation: 7941

import pandas as pd

# a minimal example often helps
d = {'country': ['Albania','Bahrain','Congo'], 'sales': [10,20,30]}
df = pd.DataFrame(data=d)

countries=['Albania','Congo']


for c in countries:
     print(df[df['country'] == c])

output:

country  sales
0  Albania     10
country  sales
2   Congo     30

Upvotes: 0

Related Questions