Miguel Ribeiro Godoy
Miguel Ribeiro Godoy

Reputation: 15

Creating N dataframes from a list

I want to create n DataFrames using the value s as the name of each DataFrame, but I only could create a list full of DataFrames. It's possible to change this list in each of the DataFrames inside it?

#estacao has something like [ABc,dfg,hil,...,xyz], and this should be the name of each DataFrame
   estacao = dados.Station.unique()
   for s,i in zip(estacao,range(126)):
     estacao[i] = dados.groupby('Station').get_group(s)

Upvotes: 0

Views: 53

Answers (2)

Pietro D'Antuono
Pietro D'Antuono

Reputation: 412

If you REALLY NEED to create DataFrames named after s (which I named group in the following example), using exec is the solution.

groups = dados.Station.unique()
groupby_ = dados.groupby('Station')

for group in groups:
    exec(f"{group} = groupby_.get_group('{group:s}')")

CAVEAT

See this answer to understand why using exec and eval commands is not always desirable.

Why should exec() and eval() be avoided?

Upvotes: 0

C.Nivs
C.Nivs

Reputation: 13106

I'd use a dictionary here. Then you can name the keys with s and the values can each be the dataframe corresponding to that group:

groups = dados.Station.unique()
groupby_ = datos.groupby('Station')

dataframes = {s: groupby_.get_group(s) for s in groups}

Then calling each one by name is as simple as:

group_df = dataframes['group_name']

Upvotes: 1

Related Questions