Sum all columns with a wildcard name search using Python Pandas Sum all columns with a wildcard name search using Python Pandas python python

Sum all columns with a wildcard name search using Python Pandas


I found the answer.

Using the data, dataframe from the question:

from pandas import *P1Channels = data.filter(regex="P1")P1Sum = P1Channels.sum(axis=1)


List comprehensions on columns allow more filters in the if condition:

In [1]: df = pd.DataFrame(np.arange(15).reshape(5, 3), columns=['P1S1', 'P1S2', 'P2S1'])In [2]: dfOut[2]:    P1S1  P1S2  P2S10     0     1     21     3     4     52     6     7     83     9    10    114    12    13    14In [3]: df.loc[:, [x for x in df.columns if x.startswith('P1')]].sum(axis=1)Out[3]: 0     11     72    133    194    25dtype: int64


Thanks for the tip jbssm, for anyone else looking for a sum total, I ended up adding .sum() at the end, so:

P1Sum= P1Channels.sum(axis=1).sum()