以“Col”开头的行按列求和

3

I have a DataFrame like this:

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

对于每一行,我想要将以Col开头的列的总值相加。是否有比下面展示的更优雅且更快的方法?

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

1
在这种情况下,df[df.columns[df.columns.str.contains('Col')]].sum(axis=1) 应该可以工作。 - EdChum
1个回答

3

试试这个

idx = df.columns.str.startswith('Col')
df['total'] = df.iloc[:,idx].sum(axis=1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接