0

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]
3
  • So you want to split the dataframe into horizontal slices , rows? Or only for a list of specific countries? Commented Sep 25, 2020 at 2:51
  • 1
    Does this answer your question? Create Pandas DataFrames from Unique Values in one Column Commented Sep 25, 2020 at 3:13
  • Could you make a minimal example where you show a specific dataframe as input and what you want your output to look like? Commented Sep 25, 2020 at 20:13

2 Answers 2

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]

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.