Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

python - All row sum with pandas except one

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

For each table, numbers and columns' names change (I created them in a loop in python).

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

I cannot use column name: the only one with no changes is gid.

Some idea to make it with python (pandas, numpy) or psql?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...