1

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

You could do something like this:

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

Bangalore = groups.get_group('Bangalore')

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.