0

I have a df in python with different cities.

enter image description here

I am trying to create a df for each city.

So wrote this code in python and it works. It does what I need. But i was wondering if there is any over way to create the name of each df in a different way rather than using

globals()\["df\_"+str(ciudad)\] = new_grouped_by

If I try this:

"df\_"+str(ciudad) = new_grouped_by

Give me this error: SyntaxError: can't assign to operator

Any tips/suggestions would be more than welcome!

def get_city():
    for ciudad in df["Ciudad"].unique():
        #print (ciudad)
        grouped_by = df.groupby('Ciudad')
        new_grouped_by=[grouped_by.get_group(ciudad) for i in grouped_by.groups]
        globals()["df_"+str(ciudad)] = new_grouped_by

get_city()
RJ Adriaansen
  • 9,131
  • 2
  • 12
  • 26
Christian
  • 3
  • 2
  • why are you trying to do this? – Chris Oct 25 '22 at 18:34
  • It is a part of my class practice. So I have differente df for ech city. If the city is called Madrid, then the df generated would be df_Madrid. Then I can access it easily. So i was wondering if there is any other way to give the names to those df. (Sorry, I am learning python since last month, so I am still no use to write in a technical way) – Christian Oct 25 '22 at 19:03

1 Answers1

0

A simple way would be to store the dataframes in a dictionary with the city names as keys:

import pandas as pd

data = zip(['Amsterdam', 'Amsterdam', 'Barcelona'],[1,22,333])
df = pd.DataFrame(data, columns=['Ciudad', 'data'])
new_dfs = dict(list(df.groupby('Ciudad')))

Calling new_dfs['Amsterdam'] will then give you the dataframe:

Ciudad data
0 Amsterdam 1
1 Amsterdam 22
RJ Adriaansen
  • 9,131
  • 2
  • 12
  • 26