Sum Of Several Columns From A Pandas Dataframe
So say I have the following table: In [2]: df = pd.DataFrame({'a': [1,2,3], 'b':[2,4,6], 'c':[1,1,1]}) In [3]: df Out[3]: a b c 0 1 2 1 1 2 4 1 2 3 6 1 I can sum a
Solution 1:
I think you can use double sum - first DataFrame.sum create Series of sums and second Series.sum get sum of Series:
print (df[['a','b']].sum())
a 6
b 12
dtype: int64
print (df[['a','b']].sum().sum())
18You can also use:
print (df[['a','b']].sum(axis=1))
031629
dtype: int64
print (df[['a','b']].sum(axis=1).sum())
18Thank you pirSquared for another solution - convert df to numpy array by values and then sum:
print (df[['a','b']].values.sum())
18print (df.sum().sum())
21Solution 2:
Maybe you are looking something like this:
df["result"] = df.apply(lambda row: row['a' : 'c'].sum(),axis=1)
Post a Comment for "Sum Of Several Columns From A Pandas Dataframe"