除一只外,所有的 pandas 行总和 [英] All row sum with pandas except one
问题描述
我在PostgreSQL数据库上有几个表,这些表看起来或多或少像这样:
I have several tables on a PostgreSQL database that look more or less like that:
gid col2 col1 col3
6 15 45 77
1 15 45 57
2 14 0.2 42
3 12 6 37
4 9 85 27
5 5 1 15
对于每个表,数字和列的名称都会更改(我在python的循环中创建了它们).
For each table, numbers and columns' names change (I created them in a loop in python).
我想为每个表返回另一列,称为sum,其中包含除gid之外的每个calumn的总和.目标是拥有类似的东西:
I would like to have back another column called sum for each table with the sum of each calumn except for the gid. The goal is having something like that:
gid col2 col1 col3 sum
6 15 45 77 137
1 15 45 57 117
2 14 0.2 42 56.2
3 12 6 37 55
4 9 85 27 121
5 5 1 15 21
我不能使用列名:唯一未更改的列是gid
.
I cannot use column name: the only one with no changes is gid
.
有人想用python
(pandas
,numpy
)或psql
做成它吗?
Some idea to make it with python
(pandas
, numpy
) or psql
?
推荐答案
df['sum'] = df.drop('gid', axis=1).sum(axis=1)
print (df)
gid col2 col1 col3 sum
0 6 15 45.0 77 137.0
1 1 15 45.0 57 117.0
2 2 14 0.2 42 56.2
3 3 12 6.0 37 55.0
4 4 9 85.0 27 121.0
5 5 5 1.0 15 21.0
如果gid
始终是第一列,请通过 iloc
所有列,而无需先sum
:
If gid
is always first column, select by iloc
all columns without first and then sum
them:
df['sum'] = df.iloc[:, 1:].sum(axis=1)
print (df)
gid col2 col1 col3 sum
0 6 15 45.0 77 137.0
1 1 15 45.0 57 117.0
2 2 14 0.2 42 56.2
3 3 12 6.0 37 55.0
4 4 9 85.0 27 121.0
5 5 5 1.0 15 21.0
这篇关于除一只外,所有的 pandas 行总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!