Skip to content
Advertisement

Assigning a string (from a list of string) to a dataframe name pandas

I have a list of names, ['name1', 'name2',... 'nameN'], that I would like to use as names for the resulting dataframes after filtering the original dataframe by each name in a for loop

name1 = originaldf[originaldf.names = 'name1']

Is there a function in python, similar to assign in R, that I can use to accomplish this. Any other solutions are welcome.

As requested. Here is an example:

names = ['name1', 'name2', 'name3']

f = pd.DataFrame({'names' : np.random.choice(names, size=15)})
name1 = df[df.names=='name1']
name2 = df[df.names=='name2']
name3 = df[df.names=='name3']

# Then: 
display(name1, name2, name3)

names
1   name1
2   name1
3   name1
4   name1
5   name1
names
0   name2
7   name2
names
6   name3
8   name3
9   name3
10  name3
11  name3
12  name3
13  name3
14  name3

Advertisement

Answer

You can use setattr for this, but i (as others) strongly recommend using a dictionary .

import sys
import pandas as pd

thismodule = sys.modules[__name__]
names = ['name1', 'name2', 'name3']

for i in names:
    setattr(thismodule, i,df[df.names==i])

display(name1,name2,name3)

This sets a dataframe to each value in names

Advertisement