I have the following 2D array, and want to take a square root of only column A.
import numpy as np
a = np.matrix([[1, 2], [3, 4], [5, 6], [7, 8]])
a
matrix([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
This is giving me sqrt of two columns. How can I only take a square root of column A?
b = np.sqrt(a[:, [0, 1]])
b
matrix([[1. , 1.41421356],
[1.73205081, 2. ],
[2.23606798, 2.44948974],
[2.64575131, 2.82842712]])
CodePudding user response:
Use out
to do in place operation
import numpy as np
a = np.matrix([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.float64)
np.sqrt(a, where=[True, False],out=a)
Output:
[[1. 2. ]
[1.73205081 4. ]
[2.23606798 6. ]
[2.64575131 8. ]]
Try it online
CodePudding user response:
I can't comment so I'm just going to have to put my answer here:
You can do it in-place with the following:
a = np.matrix([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.float)
a[:, 0] = np.sqrt(a[:, 0])
Do note that because your initial types were int
, that you must specify the dtype=np.float
if not it will all get cast to ints.
CodePudding user response:
if you want only first column, you must this
b = np.sqrt(a[:, [0]])
if you want all columns but first columns sqrt, you try this
df=pd.DataFrame(a)
df.loc[:,0]=df.loc[:,0].apply(np.sqrt)