I don't want any for loop and was wondering if there is a function I can use.
Asked
Active
Viewed 1.1k times
-1
-
Element-wise squaring? – Reti43 Apr 01 '16 at 03:53
-
Yes. [[1,2,3], [2,3,4]] becomes [[1,4,9],[2,9,16]] – Jobs Apr 01 '16 at 03:56
-
@Jobs I think you mean that list becomes `[[1,4,9],[4,9,16]]` – Anton Protopopov Apr 01 '16 at 04:29
-
Yes - you are right. @AntonProtopopov – Jobs Apr 01 '16 at 04:31
-
https://docs.scipy.org/doc/numpy-dev/user/quickstart.html#basic-operations – Warren Weckesser Apr 01 '16 at 04:36
3 Answers
5
As K. Tom suggested you can do A * A
you can also do A ** 2
import numpy as np
array = np.array([1,2,3])
print array * array #[1 4 9]
print array ** 2 #[1 4 9]

John
- 13,197
- 7
- 51
- 101
-
-
1The only thing to take care of is the type. `a = np.array([[100, 200], [50, 150]], dtype=np.uint8); a*a` will overflow. – Reti43 Apr 01 '16 at 03:59
2
You could use np.square
or np.power
:
l = [[1,2,3], [2,3,4]]
In [5]: np.power(l, 2)
Out[5]:
array([[ 1, 4, 9],
[ 4, 9, 16]], dtype=int32)
In [6]: np.square(l)
Out[6]:
array([[ 1, 4, 9],
[ 4, 9, 16]], dtype=int32)

Anton Protopopov
- 30,354
- 12
- 88
- 93