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.

2
  • Possible duplicate of How do I create a variable number of variables? Commented May 17, 2019 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 Commented May 17, 2019 at 13:34

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.