0

Hi I have a dataset looking like this.

https://i.stack.imgur.com/cjYAW.png

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

https://i.stack.imgur.com/UHkQ2.png

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

     c_df = data.loc[data.location == c]
lyngn
  • 13
  • 2
  • So you want to split the dataframe into horizontal slices , rows? Or only for a list of specific countries? – roadrunner66 Sep 25 '20 at 02:51
  • 1
    Does this answer your question? [Create Pandas DataFrames from Unique Values in one Column](https://stackoverflow.com/questions/44722436/create-pandas-dataframes-from-unique-values-in-one-column) – Trenton McKinney Sep 25 '20 at 03:13
  • Could you make a minimal example where you show a specific dataframe as input and what you want your output to look like? – roadrunner66 Sep 25 '20 at 20:13

2 Answers2

1

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]

BP34500
  • 158
  • 8
0
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
roadrunner66
  • 7,772
  • 4
  • 32
  • 38