The numpy array you are defining is not the right shape for the loop you are using. b = np.array([]) gives you an array of shape (0,)
You can use something like np.zeros to define your 2D array.
import numpy as np
b = np.zeros((3,6))
for i in range(2):
for j in range(5):
b[i][j]=i+j
print(b)
The output will be
[[0. 1. 2. 3. 4. 0.]
[1. 2. 3. 4. 5. 0.]
[0. 0. 0. 0. 0. 0.]]
Another option is to make a 2D list, fill it up in for loops, and convert to numpy array later
import numpy as np
#2D array
b = [ [0 for _ in range(6)] for _ in range(3)]
#Fill up array with for loops
for i in range(2):
for j in range(5):
b[i][j]=i+j
#Convert to numpy array
print(np.array(b))
The output will be
[[0 1 2 3 4 0]
[1 2 3 4 5 0]
[0 0 0 0 0 0]]
Answer from Devesh Kumar Singh on Stack OverflowThe numpy array you are defining is not the right shape for the loop you are using. b = np.array([]) gives you an array of shape (0,)
You can use something like np.zeros to define your 2D array.
import numpy as np
b = np.zeros((3,6))
for i in range(2):
for j in range(5):
b[i][j]=i+j
print(b)
The output will be
[[0. 1. 2. 3. 4. 0.]
[1. 2. 3. 4. 5. 0.]
[0. 0. 0. 0. 0. 0.]]
Another option is to make a 2D list, fill it up in for loops, and convert to numpy array later
import numpy as np
#2D array
b = [ [0 for _ in range(6)] for _ in range(3)]
#Fill up array with for loops
for i in range(2):
for j in range(5):
b[i][j]=i+j
#Convert to numpy array
print(np.array(b))
The output will be
[[0 1 2 3 4 0]
[1 2 3 4 5 0]
[0 0 0 0 0 0]]
I understand you asked how to do this with nested loops, so apologies if you don't find this useful. I'd just thought I'd share how I normally do this:
b = np.arange(10).reshape(2,5)
print(b)
[[0 1 2 3 4]
[5 6 7 8 9]]
The numpy array you are defining is not the right shape for the loop you are using. b = np.array([]) gives you an array of shape (0,)
You can use something like np.zeros to define your 2D array.
import numpy as np
b = np.zeros((3,6))
for i in range(2):
for j in range(5):
b[i][j]=i+j
print(b)
The output will be
[[0. 1. 2. 3. 4. 0.]
[1. 2. 3. 4. 5. 0.]
[0. 0. 0. 0. 0. 0.]]
Another option is to make a 2D list, fill it up in for loops, and convert to numpy array later
import numpy as np
#2D array
b = [ [0 for _ in range(6)] for _ in range(3)]
#Fill up array with for loops
for i in range(2):
for j in range(5):
b[i][j]=i+j
#Convert to numpy array
print(np.array(b))
The output will be
[[0 1 2 3 4 0]
[1 2 3 4 5 0]
[0 0 0 0 0 0]]
I understand you asked how to do this with nested loops, so apologies if you don't find this useful. I'd just thought I'd share how I normally do this:
b = np.arange(10).reshape(2,5)
print(b)
[[0 1 2 3 4]
[5 6 7 8 9]]
How to create 2d NumPy array with for loop [Python] - Stack Overflow
python - Create a dynamic 2D numpy array on the fly - Stack Overflow
python - How to generate 2d numpy array? - Stack Overflow
python - Initialize 2D array within loop - Stack Overflow
You can try this:
import numpy as np
listvals = []
for i in range(10):
listvals.append((xc, yc))
mat_vals = np.vstack(listvals)
This will output an ndarray like this:
[[ 2 0]
[ 3 1]
[ 4 2]
[ 5 3]
[ 6 4]
[ 7 5]
[ 8 6]
[ 9 7]
[10 8]
[11 9]]
Or this maybe is better:
import numpy as np
list_xc = []
list_yc = []
for i in np.arange(10):
list_xc.append(xc)
list_yc.append(yc)
mat_xc = np.asarray(list_xc)
mat_yc = np.asarray(list_yc)
mat_f = np.column_stack((mat_xc, mat_yc))
You can do this:
aList = []
for i in range(10):
aList.append([xc, yc])
First lets focus on the append operation,
import numpy as np
a = np.array( [1,2,3] )
b = np.array( [4,5,6] )
np.append( a, b )
produces
array( [1, 2, 3, 4, 5, 6] )
What you might want is
np.append( [a], [b], 0 )
which produces
array([ [1, 2, 3], [4, 5, 6] ])
Note that here a 0 appears in the third parameter to specify the axis for the append operation.
Regarding the error, the index h, tells numpy to append to the 'h'-th element. That's probably not what you intended. Also, the index is not correct since 'h' is always one more than the number of elements in the array at the point where the call occurs.
I think you're trying to append a value to result_array. You should try without the (h) because what that will do is try to index the value already existing in result_array at index h. But since the array is empty to start so there is no 0th value, and h=0 for the first iteration, so that's why you're getting the error.
Maybe try np.append(result_array, inter2d_result)
Create the 2D array up front, and fill the rows while looping:
my_array = numpy.empty((len(huge_list_of_lists), row_length))
for i, x in enumerate(huge_list_of_lists):
my_array[i] = create_row(x)
where create_row() returns a list or 1D NumPy array of length row_length.
Depending on what create_row() does, there might be even better approaches that avoid the Python loop altogether.
Just pass the list of lists to numpy.array, keep in mind that numpy arrays are ndarrays, so the concept to a list of lists doesn't translate to arrays of arrays it translates to a 2d array.
>>> import numpy as np
>>> a = [[1., 2., 3.], [4., 5., 6.]]
>>> b = np.array(a)
>>> b
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> b.shape
(2, 3)
Also ndarrays have nd-indexing so [1][1] becomes [1, 1] in numpy:
>>> a[1][1]
5.0
>>> b[1, 1]
5.0
Did I misunderstand your question?
You defiantly don't want to use numpy.append for something like this. Keep in mind that numpy.append has O(n) run time so if you call it n times, once for each row of your array, you end up with a O(n^2) algorithm. If you need to create the array before you know what all the content is going to be, but you know the final size, it's best to create an array using numpy.zeros(shape, dtype) and fill it in later. Similar to Sven's answer.
This works:
a = [[1, 2, 3], [4, 5, 6]]
nd_a = np.array(a)
So this should work too:
nd_a = np.array([[x for x in y] for y in a])
To create a new array, it seems numpy.zeros is the way to go
import numpy as np
a = np.zeros(shape=(x, y))
You can also set a datatype to allocate it sensibly
>>> np.zeros(shape=(5,2), dtype=np.uint8)
array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]], dtype=uint8)
>>> np.zeros(shape=(5,2), dtype="datetime64[ns]")
array([['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000']],
dtype='datetime64[ns]')
See also
- How do I create an empty array/matrix in NumPy?
- np.full(size, 0) vs. np.zeros(size) vs. np.empty()
Start with an empty list:
output_arr = []
Append within the loop:
for _ in range(5):
output_arr.append([1, 1])
Outside the loop, just call np.array:
X = np.array(output_arr)
If you really just want to construct with numpy, construct an np.empty array at the beginning, and then if you need to operate on the currently filled part of the array, use output[:i+1]
import numpy as np
output_arr = np.empty((5,2))
for i in range(0,4):
temp_arr = np.ones(2)
print temp_arr.shape
output_arr[i] = temp_arr
print output_arr[:i + 1].shape
print output_arr.shape
You could preallocate the array before assigning the respective values:
a = np.empty(shape=(25, 2), dtype=int)
for x in range(1, 6):
for y in range(1, 6):
index = (x-1)*5+(y-1)
a[index] = x, y
Did you had a look at numpy.ndindex? This could do the trick:
a = np.ndindex(6,6)
You could have some more information on Is there a Python equivalent of range(n) for multidimensional ranges?
You can perform your calculation in a vectorised fashion:
x = np.array([1,2,3,4,5])
y = np.array([5,6,7,8,9])
res = 50*x + 20*y[:, None]
array([[150, 200, 250, 300, 350],
[170, 220, 270, 320, 370],
[190, 240, 290, 340, 390],
[210, 260, 310, 360, 410],
[230, 280, 330, 380, 430]])
Here, the indexer [:, None] change the shape of y from (1,) to (5, 1). Broadcasting then allows creation of a 2d array result.
You can expect a performance improvement versus a method based on list comprehension, although you may only notice this for larger input arrays:
%timeit 50*x + 20*y[:, None] # 10.1 µs
%timeit np.array([x_*50+y_*20 for y_ in y for x_ in x]).reshape(5,5) # 30.2 µs
You don't need to pre-make the 2-d array, and you can do it all in this list comprehension:
np.array([x_*50+y_*20 for y_ in y for x_ in x]).reshape(5,5)
Which returns:
array([[150, 200, 250, 300, 350],
[170, 220, 270, 320, 370],
[190, 240, 290, 340, 390],
[210, 260, 310, 360, 410],
[230, 280, 330, 380, 430]])
First you have to install numpy using
$ pip install numpy
Then the following should work
import numpy as np
n = 100
matrix = np.zeros((n,2)) # Pre-allocate matrix
for i in range(1,n):
matrix[i,:] = [3*i, i**2]
A faster alternative:
col1 = np.arange(3,3*n,3)
col2 = np.arange(1,n)
matrix = np.hstack((col1.reshape(n-1,1), col2.reshape(n-1,1)))
Even faster, as Divakar suggested
I = np.arange(n)
matrix = np.column_stack((3*I, I**2))
This is very pythonic form to produce a list, which you can easily swap e.g. for np.array, set, generator etc.
n = 10
[[i*3, i**2] for i, i in zip(range(0,n), range(0,n))]
If you want to add another column it's no problem. Simply
[[i*3, i**2, i**(0.5)] for i, i in zip(range(0,n), range(0,n))]
I have this two arrays
array1 = [1. 0.91 0.8 0.68 0.61 0.57 0.52 0.46 0.39 0.3 ]
array2 = [188.38188649 201.69718164 210.51306563 221.65195842 229.91542541 238.11787625 257.072488 ]
I need to multiple the second array by each value in the first one. I have tried using a for loop like this
for i in range (array1):
new_array = array2 * array1[i]But it shows me this error
TypeError: only integer scalar arrays can be converted to a scalar index
Any help is appreciated, thank you.
np.column_stack can do the trick:
>>> a = np.array(range(100))
>>> b = np.column_stack((a, a**a))
>>> b
array([[ 0, 1],
[ 1, 1],
[ 2, 4],
[ 3, 27],
[ 4, 256],
[ 5, 3125],
[ 6, 46656],
[ 7, 823543],
[ 8, 16777216],
[ 9, 387420489],
[ 10, 10000000000],
[ 11, 285311670611],
[ 12, 8916100448256],
[ 13, 302875106592253],
A list comprehension could do that for you:
import numpy as np
results = np.array([[x, x**2] for x in range(100)])
That gives you an array of two columns:
Out[5]:
array([[ 0, 0],
[ 1, 1],
[ 2, 4],
[ 3, 9],
...
You've just commented that the function is more complex than just x**2 - one solution is simply to define it as a function, e.g.
import numpy as np
def func(x): # example functionality
y = x**2
y = y*2
return y
results = np.array([[x, func(x)] for x in range(100)])
Out[13]:
array([[ 0, 0],
[ 1, 2],
[ 2, 8],
[ 3, 18],
...