Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does it print array([ ]) when in a list when using an array to iterate and pull elements from?

Looking to see if I could use comprehensions or array operators, instead of for loops.

import numpy as np

a=[[1,2],[3,4]]

b=np.array(a)

c=[[x*z for x in z] for z in b[0:1]]

print(c)

OUTPUT = [[array([1, 2]), array([2, 4])]]

I want a list or array = [2,12]

I can convert list to 1D array after. Where it is first element * second element for each row in array.

I want it to work on a general case for any 2 dimensional array.

like image 275
Excubi Avatar asked Sep 20 '26 02:09

Excubi


1 Answers

Look at the action - step by step:

In [170]: b.shape                                                               
Out[170]: (2, 2)
In [171]: b[0:1]                                                                
Out[171]: array([[1, 2]])              # (1,2) array
In [172]: [z for z in b[0:1]]                                                   
Out[172]: [array([1, 2])]              # iteration on 1st, size 1 dimension
In [173]: [[x for x in z] for z in b[0:1]]                                      
Out[173]: [[1, 2]]
In [174]: [[x*z for x in z] for z in b[0:1]]                                    
Out[174]: [[array([1, 2]), array([2, 4])]]

So you are doing [1*np.array([1,2]), 2*np.array([1,2])]

With the b[0:1] slicing you aren't even touching the 2nd row of b.

But a simpler list comprehension does:

In [175]: [i*j for i,j in b]     # this iterates on the rows of b                                               
Out[175]: [2, 12]

or

In [176]: b[:,0]*b[:,1]                                                         
Out[176]: array([ 2, 12])
like image 91
hpaulj Avatar answered Sep 21 '26 20:09

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!