Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum specific columns if they exist with dataframe

Background

I have a dataframe with multiple columns. I am trying to sum all the E and B values into a single column

t_start         t_end           B1  E1      B2  E2
1/11/2021 0:00  1/11/2021 0:05  0   2.03    0   9.01
1/11/2021 0:00  1/11/2021 0:05  0   2.03    0   9.01
1/11/2021 0:00  1/11/2021 0:05  0   2.03    0   9.01

Problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thing is, the file might have 10+ E and B columns, (B1, B2, B3, etc).

What I’ve tried

I’ve tried the below, but it errors out if the columns don’t exist

df['sum_b'] = df['b1'] + df['b2'] + df['b3'] ...

I’ve also tried using a group by solution which I saw here, but it doesn’t work either, as it drops off my date columns

def left(s, amount):
    return s[:amount]

df.T.groupby([left(s, 1) for s in df.T.index.values]).sum().T)

Help Requested

If anyone knows how to make a dynamic sum formula which will add b and e columns, it would be much appreciated!

>Solution :

You can use DataFrame.filter(regex=pattern), where pattern is a regular expression designed to pick out your desired columns by name.

To select columns whose name starts with B followed immediately by a digit (thus matching B1, B2, …, B10, and so on):

df.filter(regex='^B\d')

To sum the values of all such columns:

df['sum_b'] = df.filter(regex='^B\d').sum(axis=1)
df['sum_e'] = df.filter(regex='^E\d').sum(axis=1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading