使用Python Pandas使用通配符名称搜索所有列的总和

时间:2022-09-01 23:17:28

I have a dataframe in python pandas with several columns taken from a CSV file.

我在python pandas中有一个数据框,其中有几列来自CSV文件。

For instance, data =:

例如,data =:

Day P1S1 P1S2 P1S3 P2S1 P2S2 P2S3
1   1    2    2    3    1    2
2   2    2    3    5    4    2

And what I need is to get the sum of all columns which name starts with P1... something like P1* with a wildcard.

我需要的是得到名称以P1开头的所有列的总和......类似P1 *的通配符。

Something like the following which gives an error:

像下面这样的错误:

P1Sum = data["P1*"]

P1Sum =数据[“P1 *”]

Is there any why to do this with pandas?

有没有为什么要用熊猫做这个?

2 个解决方案

#1


45  

I found the answer.

我找到了答案。

Using the data, dataframe from the question:

使用数据,来自问题的数据框:

from pandas import *

P1Channels = data.filter(regex="P1")
P1Sum = P1Channels.sum(axis=1)

#2


0  

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

感谢提示jbssm,对于其他任何寻找总和的人,我最后在最后添加了.sum(),所以:

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

#1


45  

I found the answer.

我找到了答案。

Using the data, dataframe from the question:

使用数据,来自问题的数据框:

from pandas import *

P1Channels = data.filter(regex="P1")
P1Sum = P1Channels.sum(axis=1)

#2


0  

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

感谢提示jbssm,对于其他任何寻找总和的人,我最后在最后添加了.sum(),所以:

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