Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataFrame.sum returns Series and not a number

Tags:

python

pandas

My basic task is to take vector x=[x1,x2,x3,x4] (which in my case is presented by a row of a Pandas dataframe, lets say a row with an index = 1), multiply it by scalar k and to sum up the results -> x1*k + x2*k + x3*k + x4*k.

I did not find a function that would do it in one step (Is there such a function/operation?), so i do it in two steps. First i multiply my vector x by scalar k, and then i sum up the results:

x_by_k = my_df.loc[[1]]*k
sum = x_by_k.sum(axis=1)

One of the problems i have here is that the resulting sum is of Series type, although effectively it is a number.

Is there a way to perform this sum operation with a number as an output?

Can i do the above described in one step?

like image 401
Denys Avatar asked Oct 15 '25 04:10

Denys


1 Answers

IIUC select row in df by ix, then sum and multiple by k:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9]})

print (df)
   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9

k = 2
sum = df.ix[1].sum()* k
print (sum)
30
like image 51
jezrael Avatar answered Oct 17 '25 16:10

jezrael