开发者

combining arrays

开发者 https://www.devze.com 2023-03-30 16:33 出处:网络
I have three separate 1d arrays of a list of numbers, their squares and cubes (created by a \'for\' loop).

I have three separate 1d arrays of a list of numbers, their squares and cubes (created by a 'for' loop). I would like these arrays to appear in three corresponding columns, however I have tried the column_stack function and python says its not defined. I have read about the vstack and hstack functions but am confused about which to use and what exactly they do. My code so far reads;

import numpy
makearange = lambda a: numpy.arange(int(a[0]),int(a[1]),int(a[2]))
x = makearange(raw_input('Enter start,stop,increment: ').split(','))
y = numpy.zeros(len(x), dtype=int)
z = numpy.zeros(len(x), dtype=int)
for i in range(len(x)):
    y[i] = x[i]**2
for i in range(len(x)):
    z[i] = x[i]**3
print 'original array: ',x
print 'squared array: ',y
开发者_如何转开发print 'cubed array: ', z

I would appreciate any advice


Why don't you define y and z directly?

y = x**2
z = x**3

and then simply:

stacked = np.column_stack((x,y,z))

which gives you a 2D array of shape len(x) * 3


import numpy
makearange = lambda a: numpy.arange(int(a[0]),int(a[1]),int(a[2]))
x = makearange(raw_input('Enter start,stop,increment: ').split(','))
a = np.zeros((len(x),3))
a[:,0] = x
a[:,1] = x**2
a[:,2] = x**3

When using arrays you should avoid for loops as much as possible, that's kind of the point of arrays.

a = np.zeros((len(x),3)) creates an array of length same as x and with 3 columns a[:,i] is a reference to the 'i'th column of this array (i.e. select all values (denoted by :) along this (i) column)

I would strongly recommend you look at the Numpy Tutorial.


You do want column_stack. Have you tried:

w = numpy.column_stack((x,y,z))
print(w)
0

精彩评论

暂无评论...
验证码 换一张
取 消