简体   繁体   中英

Using np.array to append into a 2D np.array

I have to read data from a file and create a new 1D np.array for each of my variables (V and T):

V = np.array([])
T = np.array([])

for ii in range(len(velocity)):
   if (velocity[ii] !=-9.999999848243207e+30 ) and (velocity[ii] != -9.999999848243207e+30):
      idx.append(ii) # create array with integer x_axis instead of time variable
V = np.append(V, np.array(velocity[idx]))
T = np.append(T, np.array(temperature[idx]))
print(V) # [630.40002441 605.29998779 611.79998779 ... 461.79998779 460.1000061
 466.8999939 ]
print(T) # [132000. 216000. 194000. ...  22100.  19300.  22200.]
# truncated because of large data set

I then try to combine these two arrays into a 2D np.array that looks like np.array([x1,y1],[x2,y2],....) :

finalV = np.array([])
for i in range(len(x_axis)):
    velocity.append(V[i])
    temp.append(T[i])
    finalV = np.append(finalV, [velocity[i], temp[i]], axis = 0)

print(finalV) # [   630.40002441 132000.            605.29998779 ...  19300.
    466.8999939   22200.        ]

As you can see I'm pretty unfamiliar with np.arrays() . First of all, should my np.array print like [x1 x2 x3] without the np.array([]) and without commas? Also, it seems like my append loop doesn't actually iterate through the array and add each one. How do I append to get a 2D np.array of the format [[x1,y1], [x2,y1],...] ?

I have done it using "list".

finalV = []
for i in range(len(x_axis)):
    finalV.append([V[i],T[i]])
print(finalV)

you can apply same concept on NumPy arrays.

Concept:

to append a list:

finalV.append([])

to append an array:

np.append(finalV, np.array(V[i],T[i]), axis=None)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM