0

I am trying to generate multiple pandas data frames within a loop, I am having difficulty with the variable definitions though. The first iteration of str(test[i-1]) returns A, so I assumed I could concatenate this string with another string to create a variable, the first variable should be defined as A_data_columns=['Test1','Test2'] however this throws an error (which I half expected), I was just wondering if there is a way to do this properly, or perhaps a better way?

test=[]
for i in range(1,5):
    test.append(chr(ord('@')+i))
    str(test[i-1])+'_data_columns'=['Test1', 'Test2']
    str(test[i-1])+'_dataframe'=pd.DataFrame(columns=str(test[i-1])+'_data_columns')
    str(test[i-1])+'_dataframe'
    
    
    

Error:

SyntaxError: cannot assign to operator

1 Answer 1

1

str(test[i-1])+'_data_columns' is a string, and not a variable name. You cannot assign a value to the string, it makes no sense.

One way to solve this would be to use a dictionary. In this way you can map a string to an object, which is what you are trying to do.

test=[]
test_dict = dict()
for i in range(1,5):
    test.append(chr(ord('@')+i))
    test_dict[str(test[i-1])+'_data_columns'] = ['Test1', 'Test2']
    test_dict[str(test[i-1])+'_dataframe'] = pd.DataFrame(columns=str(test[i-1])+'_data_columns')

You can then access the values as follows:

print(test_dict['A_data_columns'])
# should print ['Test1', 'Test2']
Sign up to request clarification or add additional context in comments.

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.