Home > front end >  How to convert pandas DataFrame to multiple DataFrame?
How to convert pandas DataFrame to multiple DataFrame?

Time:06-29

My DataFrame

df= pandas.DataFrame({
  "City" :["Chennai","Banglore","Mumbai","Delhi","Chennai","Banglore","Mumbai","Delhi"],
  "Name" :["Praveen","Dhansekar","Naveen","Kumar","SelvaRani","Nithya","Suji","Konsy"]
  "Gender":["M","M","M","M","F","F","F","F"]})

when printed it appears like this, df=

City Name Gender
Chennai Praveen M
Banglore Dhansekar M
Mumbai Naveen M
Delhi Kumar M
Chennai SelvaRani F
Banglore Nithya F
Mumbai Suji F
Delhi Konsy F

I want to save the data in separate DataFrame as follows:

Chennai=

City Name Gender
Chennai Praveen M
Chennai SelvaRani F

Banglore=

City Name Gender
Banglore Dhansekar M
Banglore Nithya F

Mumbai=

City Name Gender
Mumbai Naveen M
Mumbai Suji F

Delhi=

City Name Gender
Delhi Kumar M
Delhi Konsy F
My code is:

D_name= sorted(df['City'].unique())
for i in D_name:
   f"{i}"=df[df['City']==I]

The dataset have more than 100 Cities.How do I write a for loop in python to get output as multiple data frame?

CodePudding user response:

You can groupby and create a dictionary like so:

dict_dfs = dict(iter(df.groupby("City")))

Then you can directly access individual cities:

Delhi = dict_dfs["Delhi"]
print(Delhi)

# result:

    City   Name Gender
3  Delhi  Kumar      M
7  Delhi  Konsy      F

CodePudding user response:

You could do something like this:

groups = df.groupby(by='City')

Bangalore = groups.get_group('Bangalore')
  • Related