A2N15
A2N15

Reputation: 605

Create One Dataframe per unique Values in Pandas

Hello World,

I would to create One Dataframe per unique value from one column.

Below is my initial Dataframe.

Date     Name     Value
01/19     Jean        15
01/19     Jean        15
01/17     Bean        15
01/16     Bean        15
01/19     Jean        15

I have found some answers concerning the creation of dataframes based on unique values, such as : Create Pandas DataFrames from Unique Values in one Column.

With the following code, I am having everything within a list.

dfa = [x for _, x in df.groupby('name')]
dfa[0]

output 
Date     Name     Value
01/19     Jean        15
01/19     Jean        15
01/19     Jean        15
Date     Name     Value
01/17     Bean        15
01/16     Bean        15    

However, I would like to assign the name of dataframe automatically and not doing:

df_Jean= df[0]
df_Bean= df[1]

Below are the expected output

df_Jean
Date     Name     Value
01/19     Jean        15
01/19     Jean        15
01/19     Jean        15

Upvotes: 2

Views: 318

Answers (2)

Alon
Alon

Reputation: 11895

You should use a dict:

d = {k:v for k, v in df.groupby("Name")}

Then you can simply pass the names as key:

print (d["Jean"])

    Date  Name  Value
0  01/19  Jean     15
1  01/19  Jean     15
4  01/19  Jean     15

Upvotes: 2

jezrael
jezrael

Reputation: 862671

It is possible, but not recommended in python:

for i, g in df.groupby('name'):
    globals()['df_' + str(i)] =  g

Or:

for i, g in df.groupby('name'):
    globals()[f'df_{i}'] =  g

Better is use dict:

d = dict(tuple(df.groupby("Name")))

print (d['Jean'])
print (d['Bean'])

Upvotes: 1

Related Questions