Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve sign when squaring values in dataframe

Tags:

python

pandas

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?

like image 882
Jaffer Wilson Avatar asked Jan 27 '23 08:01

Jaffer Wilson


1 Answers

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
like image 174
jezrael Avatar answered Jan 28 '23 21:01

jezrael