简体   繁体   中英

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

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

I had the same problem. In Python to create a dataframe based on a name stored as a string you can use globals() like this:

name = 'name1'
globals()[name] = df

In this example, df is the copy of the dataframe you're trying to rename, so in your example that should be:

names = ['name1', 'name2', 'name3']
for n in names:
    globals()[n] = df[df.names==n]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM