Reputation: 2698
import numpy as np
from scipy import stats
np.random.seed(42)
data = sorted(stats.norm.rvs(size=1000))
I want to raise data
to the power of 3/4.
I tried:
np.power(data, 3/4) # doesn't work because power is not integer
np.float_power(data, 3/4) # returns nan for negative elements
scipy.linalg.fractional_matrix_power(data, 3/4) # doesn't work because data is 1D array, not matrix
How can I do this using numpy?
Upvotes: 0
Views: 1498
Reputation: 19885
There is no need to call, say, np.power
explicitly; by performing your computations before using sorted
(or even using np.sort
instead), we can just use operators:
np.sort(data ** (3 / 4))
Necessarily, this will give nan
values because a root of a negative number will be complex, and your array can only handle floats
.
The solution is therefore to cast it to dtype np.complex
:
data = np.sort(stats.norm.rvs(size=10).astype(np.complex) ** (3 / 4))
print(data)
Output:
[-1.18840462+1.18840462j -0.10707968+0.10707968j -0.09787584+0.09787584j
-0.05992208+0.05992208j 0.10880864+0.j 0.1484953 +0.j
0.45161317+0.j 0.78783041+0.j 0.79189574+0.j
0.93656538+0.j ]
Upvotes: 1
Reputation: 1434
np.power(data, 3./4)
will result in a float for the power. Since 3/4 will return an int.
Upvotes: 2