Jordan
Jordan

Reputation: 1495

How to name each dataframe developed in a for loop by a list value

I have a pandas dataframe where I want to filter to 10 different dataframes based on unique values in a column. I have a list of those values and would like to dynamically name each filtered dataframe by the name it's filtered on.

Here is some example code:

import pandas as pd

df = {'value':[1,1,1,1,2,2,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,5,5,5],
      'value2':['a','a','a','a','b','b','c','c','c','c','c','c','c','d','d','d','d','e','e','e','e','e','e','e']}

df1 = pd.DataFrame(df)

value2 = ['a','b','c','d','e']

for value in value2:
    value = df1[df1['value2'] == value]

So the end result would be five dataframes named for each value in the list value2, filtered to all observations from df1 that are also from value2.

Upvotes: 0

Views: 261

Answers (1)

Darina
Darina

Reputation: 1631

It would be easier to create a dictionary:

dfs = {}
for value in value2:
    dfs[value] = df1[df1['value2'] == value]

Then if you want to access them from outside you can simply query dfs[value].

Upvotes: 1

Related Questions