1

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

J.Doe
  • 143
  • 7
  • 1
    Can you please provide an example of an input and a desired output? – DSCH Nov 30 '17 at 13:13
  • Your approach is correct. you can check this post to assign names dynamically. https://stackoverflow.com/questions/4010840/generating-variable-names-on-fly-in-python – Sumit S Chawla Nov 30 '17 at 13:34
  • 2
    Typically you wouldn't use single standalone variables at all in this case. You could use a `list` instead, and then fill it with `append` in the loop. Indexing etc. then becomes way easier, too – Jeronimo Nov 30 '17 at 13:34
  • Thankyou for your time. I have tried `assignments = [Data.columns[:,i+1] for i in range(1,len(cols)-1)]` resulting in the python error `IndexError: too many indices for array`. I played around with your code and got `assignments = [correctedgrades.columns for i in range(2,len(cols))]`, this resulted in this; `[RangeIndex(start=0, stop=5, step=1), RangeIndex(start=0, stop=5, step=1), RangeIndex(start=0, stop=5, step=1)]` How would one get it to start at column 3 ( start =2)? – J.Doe Dec 07 '17 at 08:45

1 Answers1

0

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].

colopop
  • 441
  • 3
  • 13
  • Thankyou for your time **colopop**. I have tried `assignments = [Data.columns[:,i+1] for i in range(1,len(cols)-1)]` resulting in the python error `IndexError: too many indices for array`. – J.Doe Dec 07 '17 at 08:36