I have tried this:
>>> (-10) ** 2
100
>>> -10 ** 2
-100
In short, I was trying to get the output of the negative values squaring as negative.
So I tried the above simple expressions.
Then I tried the same formula on Pandas DataFrame, but I received ll the positive values.
>>> listi = [-10,-2,2,3,4,5,-100,-3,4]
>>> import pandas as pd
>>> df = pd.DataFrame(listi)
>>> df
0
0 -10
1 -2
2 2
3 3
4 4
5 5
6 -100
7 -3
8 4
>>> df**2
0
0 100
1 4
2 4
3 9
4 16
5 25
6 10000
7 9
8 16
I want to know why this happened? And how I can keep the squaring of the negative values as negative using pandas?
You can multiple values by numpy.sign
for -1
for negative values:
print (df**2 * np.sign(df))
0
0 -100
1 -4
2 4
3 9
4 16
5 25
6 -10000
7 -9
8 16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With