Whole sum of rows with pandas except one

I have several tables in a PostgreSQL database that look something like this:

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

      

For each table, the name and column names change (I created them in a loop in python).

I would like to return another column called the sum for each table with the sum of each calmin besides gid. The goal is as follows:

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

      

I can't use the column name: the only one unchanged is gid

.

Some idea to do this with python

( pandas

, numpy

) or psql

?

+3


source to share


1 answer


Use drop

+ sum

:

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

      



If gid

always the first column, select iloc

all columns without the first and then sum

these:

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

      

+9


source







All Articles