1

I've got a dataframe (questDay1Df) where I want to sum up the values per row of 21 columns into a new column (BDI_SUM)

I know how to do it by calling and adding each column-value:

questDay1Df['BDI_SUM'] = questDay1Df['BD01']+questDay1Df['BD02']+questDay1Df['BD03']+questDay1Df['BD04']+questDay1Df['BD05']+questDay1Df['BD06']+questDay1Df['BD07']+questDay1Df['BD08']+questDay1Df['BD09']+questDay1Df['BD10']+questDay1Df['BD11']+questDay1Df['BD12']+questDay1Df['BD13']+questDay1Df['BD14']+questDay1Df['BD15']+questDay1Df['BD16']+questDay1Df['BD17']+questDay1Df['BD18']+questDay1Df['BD19']+questDay1Df['BD20']+questDay1Df['BD21']

Is there a quicker way in which I wouldn't have to write down each column name? BD01-BD21 are all next to each other in the data frame. My idea was to call the column number of BD01 because I am not too sure of it's number and then just write a code to sum up the row-values for this column and the next 20 columns but I wasn't able to implement that now.

TIA for any ideas :)

Wasif
  • 14,755
  • 3
  • 14
  • 34
valid
  • 63
  • 6
  • `filter()` will work here `df.filter(like='BD').sum(axis=1)` – Umar.H Nov 06 '20 at 09:57
  • Does this answer your question? [Find column whose name contains a specific string](https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string) – Umar.H Nov 06 '20 at 10:00

1 Answers1

2

Yeah, use df.sum along axis 1 (column wise):

questDay1Df['BDI_SUM'] = questDay1Df.sum(axis=1)

If you need to filter columns:

questDay1Df['BDI_SUM'] = questDay1Df.filter(regex='BD\d+$').sum(axis=1)

You can use like too in filter: .filter(like='BD')

Wasif
  • 14,755
  • 3
  • 14
  • 34