Sum Value In A Row Based On The Head Of The Columns
I have a dataset like this: I want to calculate the sum of apple_*_C,apple_*_Cr, apple_*_Cu in each row, respectively, with the following code. for test in ['apple']: df[f'{te
Solution 1:
import pandas as pd
data = {
"Apple_1_C" : [1,2],
"Apple_2_C" : [2,3],
"Apple_3_C" : [3,4],
"Apple_1_Cr" : [4,5],
"Apple_1_Cr" : [5,6],
"Apple_1_Cu" : [6,7],
"Apple_2_Cu" : [7,8],
}
df = pd.DataFrame(data)
df
for i, test inenumerate(['Apple']):
df[f'{test}_C_sum']=df.filter(regex=f'^{test}_\d_C$').sum(1)
df[f'{test}_Cr_sum']=df.filter(regex=f'^{test}_\d_Cr').sum(1)
df[f'{test}_Cu_sum']=df.filter(regex=f'^{test}_\d_Cu').sum(1)
df
Post a Comment for "Sum Value In A Row Based On The Head Of The Columns"