1

I have a for loop, in which I want to call a different pd.Dataframes in each loop and add a certain column ('feedin') to another dataframe. The variable name consists of 'feedin_' + x. Lets say a,b and c. So in the first loop I want to call the variable feedin_a and add the column 'feedin' to the new dataframe. In the next feedin_b and so on.

I pass a list of ['a', 'b', 'c'] and try to combine feedin_+ a. But since the list consists of string parameters it wont call the variable

feedin_a = pd.Dataframe
feedin_b = pd.Dataframe
feedin_c = pd.Dataframe

list = ['a', 'b', 'c']

for name in list:

df.new['feedin_'+name] = 'feedin_'+name['feedin']

Which doesnt work because the variable is called as a string. I hope you get my problem.

mao95
  • 1,046
  • 12
  • 21
Elias
  • 115
  • 1
  • 8
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Nick is tired May 17 '19 at 13:30
  • well the dictionary would work, but as you can see I need the 'a' one time as a string to call the new column and one time to call the variable – Elias May 17 '19 at 13:34

3 Answers3

0

This is one of the reasons it's not a great idea to use variables feedin_a, feedin_b, when you really need a data structure like a list.

If you can't change this, you can looking up the names in the locals() (or globals() dictionary:

df.new['feedin_'+name] = locals()['feedin_'+name]['feedin']
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You can use locals() so it should be something like that:

feedin_a = pd.Dataframe
feedin_b = pd.Dataframe
feedin_c = pd.Dataframe

name_list = ['a', 'b', 'c']

for name in list:
    key = 'feedin_{}'.format(name)
    df.new[key] = locals()[key]

also check this Python, using two variables in getattr?

p.s. do not use list as variable name because it is built-in python object

The Hog
  • 889
  • 10
  • 26
0

Others have answered your exact question by using locals(). In the comments someone pointed out another way to achieve the thing you're after: using a dictionary to hold your "variable names" as string that can be looked up with string manipulation.

import pandas as pd

dataframes = dict()

letter_list = ['a', 'b', 'c']
for letter in letter_list:
    dataframes['feedin_'+letter] = pd.DataFrame()

for name in letter_list:
    dataframes['feedin_'+name].insert(0, 'feedin_'+name, None)

print(dataframes)
{'feedin_a': Empty DataFrame
Columns: [feedin_a]
Index: [], 'feedin_b': Empty DataFrame
Columns: [feedin_b]
Index: [], 'feedin_c': Empty DataFrame
Columns: [feedin_c]
Index: []}

If you intend to do a lot of calling your DataFrames by string manipulation, this is a good way to go.

user1717828
  • 7,122
  • 8
  • 34
  • 59