简体   繁体   中英

Summing 3 columns in a dataframe

This should be easy:

I have a data frame with the following columns

a,b,min,w,w_min 

all I want to do is sum up the columns min,w,and w_min and read that result into another data frame.

I've looked, but I can not find a previously asked question that directly relates back to this. Everything I've found seems much more complex then what I'm trying to do.

You can just pass a list of cols and select these to perform the summation on:

In [64]:
df = pd.DataFrame(columns=['a','b','min','w','w_min'], data = np.random.randn(10,5) )
df

Out[64]:
          a         b       min         w     w_min
0  0.626671  0.850726  0.539850 -0.669130 -1.227742
1  0.856717  2.108739 -0.079023 -1.107422 -1.417046
2 -1.116149 -0.013082  0.871393 -1.681556 -0.170569
3 -0.944121 -2.394906 -0.454649  0.632995  1.661580
4  0.590963  0.751912  0.395514  0.580653  0.573801
5 -1.661095 -0.592036 -1.278102 -0.723079  0.051083
6  0.300866 -0.060604  0.606705  1.412149  0.916915
7 -1.640530 -0.398978  0.133140 -0.628777 -0.464620
8  0.734518  1.230869 -1.177326 -0.544876  0.244702
9 -1.300137  1.328613 -1.301202  0.951401 -0.693154

In [65]:    
cols=['min','w','w_min']
df[cols].sum()

Out[65]:
min     -1.743700
w       -1.777642
w_min   -0.525050
dtype: float64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM