In the code below I tried to use np.append
but it only gives me the last value appended in the loop.
I have two nested for loops (one runs with index i
, the other one with k
). Now I want to exercise a certain function for different indices and I want the outcomes to be summarized in one array. So that each line in the array contains the outcome for one index.
Here a minimal reproducible example:
import numpy as np
a = np.arange(0,2,1)
b = np.arange(3,5,1)
c = np.array([])
for i in range(0,2,1):
for k in range(0,2,1):
c = np.append(a[i],b[k])
print(c)
The outcome is [1 4]
. But I want one single vector c
containing ([0 3][0 4][1 3][1 4])
You are confused with syntax for np.append()
Use below for correct implementation:
c = np.append(c,[a[i],b[k]])
Also for that you will get the output printed as:
[0. 3. 0. 4. 1. 3. 1. 4.]
I'm confused for the vector you are talking about: ([0 3][0 4][1 3][1 4])
The representation stated by you is not a vector but seems as a matrix with dimension 4x2
, where .reshape() might help you.
If you want that just write: c.reshape((4,2))
which will get you:
[[0. 3.]
[0. 4.]
[1. 3.]
[1. 4.]]
You are creating 1d array instead of 2d. and in np.append
you have to pass current array and appending elements and it will return a new array.
a = np.arange(0,2,1)
b = np.arange(3,5,1)
c = np.empty(shape=[0, 2])
for i in range(0,2,1):
for k in range(0,2,1):
c = np.append(c,[[a[i],b[k]]],axis=0)
print(c)
Outptut:
[[0. 3.]
[0. 4.]
[1. 3.]
[1. 4.]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.