Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square of each element of a column in pandas

Tags:

python

pandas

How can I square each element of a column/series of a DataFrame in pandas (and create another column to hold the result)?

like image 774
Pierpaolo Avatar asked Dec 17 '13 20:12

Pierpaolo


People also ask

How do you take the square root of a column in Python?

To calculate the square root in Python, you can use the built-in math library's sqrt() function.

What does ILOC [] do in Python?

The iloc() function in python is defined in the Pandas module that helps us to select a specific row or column from the data set. Using the iloc method in python, we can easily retrieve any particular value from a row or column by using index values.


3 Answers

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2],[3,4]], columns=list('ab'))
>>> df
   a  b
0  1  2
1  3  4
>>> df['c'] = df['b']**2
>>> df
   a  b   c
0  1  2   4
1  3  4  16
like image 86
alko Avatar answered Oct 09 '22 14:10

alko


Nothing wrong with the accepted answer, there is also:

df = pd.DataFrame({'a': range(0,100)})
np.square(df)
np.power(df, 2)

Which is ever so slightly faster:

In [11]: %timeit df ** 2
10000 loops, best of 3: 95.9 µs per loop

In [13]: %timeit np.square(df)
10000 loops, best of 3: 85 µs per loop

In [15]: %timeit np.power(df, 2)
10000 loops, best of 3: 85.6 µs per loop
like image 33
postelrich Avatar answered Oct 09 '22 15:10

postelrich


You can also use pandas.DataFrame.pow() method.

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2], [3,4]], columns=list('ab'))
>>> df
   a  b
0  1  2
1  3  4
>>> df['c'] = df['b'].pow(2)
>>> df
   a  b   c
0  1  2   4
1  3  4  16
like image 6
Jaroslav Bezděk Avatar answered Oct 09 '22 14:10

Jaroslav Bezděk