Heinz - 3 months ago 29

Python Question

The following code contains PostGIS query and get 'product', which includes integer and floats,

`import numpy`

k = 8

for i in cor_list:

for l in cor_list:

cur.execute(query, (i, l, False, False))

element = cur.fetchall()

product = sum([a[-1] for a in element[:-1]])

print product

ss = numpy.array(product, ndmin = 2)

kk = ss.reshape((k,k))

part of product looks like:

`0`

6460.51962839

16386.3142965

18349.9662043

13071.5492165

8349.95786602

3977.69337529

10471.7888158

6460.51962839

0

9925.79466809

11889.4465759

and I want to arrange these product in a numpy array which is 8 times 8, which could looks like,

but as I ran the code above, I got this error:

`ValueError: total size of new array must be unchanged`

How to store integer and float generated by for-loop in numpy array in matrix form?

Answer

I think you can fix your code by doing something like this:

```
import numpy
product = []
k = 8
for i in cor_list:
for l in cor_list:
cur.execute(query, (i, l, False, False))
element = cur.fetchall()
product.append( sum([a[-1] for a in element[:-1]]) )
kk = numpy.array(product).reshape((k,k))
```