Alí Meres Vargas
Alí Meres Vargas

Reputation: 51

Creating arrays with a loop (Python)

I am trying to create several arrays from a big array that I have. What I mean is:

data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], 
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 0, 0, 0,1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0], 
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0]]  

I want to create 10 different arrays - using the 10 data's columns - with different names.

data1 = [0, 0, 0, 1, 0, 0, 1, 0, 0],
data2 = [1, 0, 1, 0, 0, 0, 0, 1, 0], and so on

I found a close solution here - Also I take the example data from there - However, when I tried the solution suggested:

for d in xrange(0,9):
exec 'x%s = data[:,%s]' %(d,d-1)

A error message appears:

exec(code_obj, self.user_global_ns, self.user_ns)

  File "", line 2, in 
    exec ('x%s = data[:,%s]') %(d,d-1)

  File "", line 1
    x%s = data[:,%s]
                 ^
SyntaxError: invalid syntax

Please, any comments will be highly appreciated. Regards

Upvotes: 0

Views: 1059

Answers (4)

  1. I don't see the proper indentation in your for loop.

  2. I suggest you don't use %s for the second argument (string) but rather %d (number) since you need a number to do the indexing of your array.

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153460

Use numpy array index:

data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], 
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 0, 0, 0,1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0], 
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0]]

d = np.array(data)

d[:, 0]
#array([0, 0, 0, 1, 0, 0, 1, 0, 0])

d[:, 1]
#array([1, 0, 1, 0, 0, 0, 0, 1, 0])

etc...

d[:, 9]
#array([0, 0, 1, 1, 1, 0, 0, 0, 0])

If you must, then dictionaries are the way to go:

val = {i:d[:,i] for i in range(d.shape[1])}

To access the arrays:

val[0]
#array([0, 0, 0, 1, 0, 0, 1, 0, 0])

...

val[9] 
#array([0, 0, 1, 1, 1, 0, 0, 0, 0])

Upvotes: 1

Anuj Sharma
Anuj Sharma

Reputation: 537

Either use numpy array as shown by scott boston above or use dictionary like this:

a = {}

for i in range(0,9):
    a[i] = data[i][:]

Output:

{0: [0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
 1: [0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
 2: [0, 1, 1, 0, 0, 0, 0, 0, 0, 1],...

Upvotes: 0

Code Pope
Code Pope

Reputation: 5449

Use the following code (it is also more readable -- for python 3.x) if you really want to create dynamic variables:

for d in range(0,9):
  # exec 'x%s = data[:,%s]' %(d,d-1)
  exec(f"data{d} = {data[d]}" )

Upvotes: 0

Related Questions