Back
How can I square each element of a column/series of a DataFrame in pandas (and create another column to hold the result)?
The following piece of code works for me:
>>> import pandas as pd>>> df = pd.DataFrame([[1,2],[3,4]], columns=list('ab'))>>> df a b0 1 21 3 4>>> df['c'] = df['b']**2>>> df a b c0 1 2 41 3 4 16
>>> 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
a b c
0 1 2 4
1 3 4 16
If you wish to Learn more about Pandas visit this Pandas Tutorial.
31k questions
32.8k answers
501 comments
693 users