3

I have a DataFrame like this:

df =
  Col1  Col2  T3  T5
  ------------------
  28    34    11  22
  45    589   33  66

For each row I want to sum up the total values of columns whose names start with Col. Is there some more elegant and quick way than the one shown below?

df['total'] = 0
for index, row in df.iterrows():
    total_for_row = 0
    for column_name, column in df.transpose().iterrows():
        if 'Col' in column_name:
            total_for_row = total_for_row + row[column_name]
    row['total'] = total_for_row
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217

1 Answers1

3

Try this

idx = df.columns.str.startswith('Col')
df['total'] = df.iloc[:,idx].sum(axis=1)
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72