Sum specific columns for selected rows with a specific value

Viewed 51

I am trying to sum a list of columns (colart2015) for specific rows. I can't figure out what is wrong with my code:

# first Select the columns that I want to sum
colart2015 = ['Column1', 
              'Column6',
              'Column10']

# then apply I select the row for the column 'Year' that match the value '2015' and sum the list of columns 'colart2015'

df_pivotms['totalart'] = df_pivotms.loc[df_pivotms['Year'] =='2015'], [colart2015].sum(axis =1) 

I have got the following error:

'list' object has no attribute 'sum'

1 Answers

There is [] mismatch, use:

df_pivotms['totalart'] = df_pivotms.loc[df_pivotms['Year']=='2015', colart2015].sum(axis=1)

If year is integer:

df_pivotms['totalart'] = df_pivotms.loc[df_pivotms['Year']==2015, colart2015].sum(axis=1)
Related