Square of each element of a column in pandas

Question:

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

Asked By: Pierpaolo

||

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
Answered By: 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
Answered By: 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
Answered By: Jaroslav Bezděk

what if I want to hold the squares of say 2 different colums and hold them in two different columns. Is there a one-line pandas function that can handle that?
or should I write them one by one line?

Answered By: Mehmet Deniz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.