Assigning variable names with a 'for' loop in Python, when number of variables is unknown

2.4k Views Asked by At

I am new to Python and Stacks Overflow. I am trying to assign variabel names to 1 dimensional arrays of columns in a np. matrix dataset. The amount of total data columns is unknown, so I cannot name the columns manually. I do however know that the columns of interest start with the third column of the dataset, i.e they start from -Data[:,2]-. My question is; how do I assign variabel names to all the 'column-arrays' of interest when the total amount of columns is unknown? I.e

Assignment 1 = Data[:,2]
Assignment 2 = Data[:,3]
Assignment 3 = Data[:,4]
Assignment 4 = Data[:,5]
...
Assignment N = Data[:,N+1]

I have tried using a for loop... !THE FOLLOWING CODE DOES NOT WORK!

# Create index, to compute the amount of columns of interest. "Data" is a np
# array 

    cols= Data.columns[2:]

# i from column 2 to last column 

    for i in range(2,(len(cols))):

        +Assigment(i-1) = Data[:,i]
        # Variabel name = 'slice' of column data

My input looks like this;

Input "Data" numpy matrix

Desired output would be a one-dimensional array of column values, i.e

Desired 1 dim. array output

Any thoughts would be greatly appreciated.

Python 3.6.1 64bits, Qt 5.6.2, PyQt5 5.6 on Darwin

1

There are 1 best solutions below

1
On

You don't want to assign variable names on the fly. You want a list. You can construct it with a list comprehension:

assignments = [Data.columns[:,i+1] for i in range(1,len(cols)-1)]

Then you can use this list in, e.g., a loop like this:

for assignment in assignments:
   #do something

You can also access Assignment i with assignments[i].