pythondataframesumsquare

How to calculate sum of squares of each cell for a row in dataframe?


i have a dataframe like this

Index A B C D E
0 4 2 4 4 1
1 1 4 1 4 4
2 3 1 2 0 1
3 1 0 2 2 4
4 0 1 1 0 2

i want to take the square for each cell in a row and add them up then put the result in a column "sum of squares", how to do that ?

i expect this result :

Index A B C D E sum of squares
0 4 2 4 4 1 53
1 1 4 1 4 4 50
2 3 1 2 0 1 15
3 1 0 2 2 4 25
4 0 1 1 0 2 6

Solution

  • By using apply() and sum().

    Code:-

    import pandas as pd
    lis=[(4,2,4,4,1),
         (1,4,1,4,4),
         (3,1,2,0,1),
         (1,0,2,2,4),
         (0,1,1,0,2)]
    df = pd.DataFrame(lis)
    df.columns =['A', 'B', 'C', 'D','E']
    #print(df)
    
    # Main code
    new=df.apply(lambda num: num**2) #Square of each number stored in new.
    
    #Creating new column sum_of_squares applying sum() function on new
    df['sum_of_squares']=new.sum(axis=1)
    
    print(df)
    

    Output:-

       A  B  C  D  E  sum_of_squares
    0  4  2  4  4  1              53
    1  1  4  1  4  4              50
    2  3  1  2  0  1              15
    3  1  0  2  2  4              25
    4  0  1  1  0  2               6