0

I need to create several arrays from a vector x. Each element in the vector needs to be of the power 0,1,2,...,n. A array with 3 elements should yield 3 arrays, with power 0,1,2.

x=numpy.array([1,2,3])
n=len(x)
for i in range(n):
    print(x**i)

Yields:

[1 1 1]
[1 2 3]
[1 4 9]

When I would like to have:

array([1, 1, 1]),
array([1, 2, 3]),
array([1, 4, 9])

4 Answers4

0

As I understand your question, you want a 2D numpy array containing all the raised numpy arrays:

import numpy
x=numpy.array([1,2,3])
print numpy.array([x**i for i in range(len(x))])
EvenLisle
  • 4,672
  • 3
  • 24
  • 47
0

I solved it myself. I have tried something similar to this, but probably not entirely. This solves my problem

x=numpy.array([1,2,3])
n=len(x)
f = []
for i in range(n):
    f.append(x**i)  
0

I hope following will work for you

x = np.arange(5)    
powr = [1,2,3]    
np.array([x**i for i in powr])

array([[ 0,  1,  2,  3,  4],
       [ 0,  1,  4,  9, 16],
       [ 0,  1,  8, 27, 64]])
vrajs5
  • 4,066
  • 1
  • 27
  • 44
0

What you print are numpy arrays, it's just that print uses the string representation as returned from the str builtin. What you want is the string returned by the repr builtin (see Difference between str and repr in Python for detailed discussion of the issues involved).

Try this code and appreciate the similarities and the differences

import numpy

x=numpy.array([1,2,3])
n=len(x)
for i in range(n):
    print(x**i)
    print(str(x**i))
    print(repr(x**i))
Community
  • 1
  • 1
gboffi
  • 22,939
  • 8
  • 54
  • 85