pythonloopsmultiple-variable-return

Python loop to update multiple variables


Assume a, b, c, d are all pre-existing pandas dataframes.

I would like to create a loop that converts each of these dataframes into numpy arrays and then print a message stating the shape of the array (and ideally a message like "The shape of array 'b' is ..." etc). Importantly, I would like to re-use the original variable names for the new numpy arrays

I've tried a few variations of the following:

data = [a, b, c, d] 

for i in range (len(data)):
   data[i] = data[i].values
   print('The shape of array xx is' + str(data[i].shape))
   

The problem with the above is that while it updates the contents of the list, the original dataframes themselves (a,b,c,d) are not updated, and I'm not exactly sure how to reference the variable name from the list when printing the message. I could probably write some follow-up code in which a = data[0] etc, but that seems inefficient.

I think this ought to be easy, but I haven't had much luck searching ... Thanks in advance


Solution

  • It is not suggested to use exec but this answers your question

    for i in list("abcd"):
        exec(f'{i} = {i}.values')
    

    Also, if you want to print the shape

    for i in list("abcd"):
        exec(f'{i} = {i}.values')
        exec(f'shape = {i}.shape')
        print(f'The shape of array {i} is {shape}')