简体   繁体   中英

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

i have a dataframe like this

    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:

    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   

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM