Calculate Sum in Python (Examples) NumPy & pandas List Object, One Particular Column & by Group

Channel Avatar
Comment
X
Share
Calculate Sum in Python (Examples) NumPy & pandas List Object, One Particular Column & by Group
Calculate Sum in Python (Examples) NumPy & pandas List Object, One Particular Column & by Group
How to calculate the sum of a list or a pandas DataFrame column in the Python programming language. More details: https://statisticsglobe.com/calculate-sum-python
Python code of this video:

my_list [1, 4, 3, 9, 1, 3, 5, 7, 3, 2, 1] # Create example list
print(my_list) # Print example list
# [1, 4, 3, 9, 1, 3, 5, 7, 3, 2, 1]

import numpy as np # Load NumPy library

print(np.sum(my_list)) # Get sum of list
# 39

import pandas as pd # Import pandas library to Python

data pd.DataFrame({‘x1’:[5, 2, 7, 3, 1, 4, 2, 3, 1, 1, 7, 5], # Create pandas DataFrame
‘x2’:range(10, 22),
‘group’:[‘A’, ‘A’, ‘B’, ‘B’, ‘C’, ‘C’, ‘A’, ‘A’, ‘C’, ‘A’, ‘B’, ‘A’]})
print(data) # Print pandas DataFrame

print(data[‘x1’].sum()) # Get sum of one column
# 41

print(data.sum()) # Get sum of all columns
# x1 41
# x2 186
# group AABBCCAACABA
# dtype: object

print(data.sum(axis 1)) # Get sum of rows
# 0 15
# 1 13
# 2 19
# 3 16
# 4 15
# 5 19
# 6 18
# 7 20
# 8 19
# 9 20
# 10 27
# 11 26
# dtype: int64

print(data.groupby(‘group’).sum()) # Get sum by group
# x1 x2
# group
# A 18 94
# B 17 45
# C 6 47

Follow me on Social Media:
Facebook – Statistics Globe Page: https://www.facebook.com/statisticsglobecom/
Facebook – Group for Discussions & Questions: https://www.facebook.com/groups/statisticsglobe
LinkedIn – Statistics Globe Page: https://www.linkedin.com/company/statisticsglobe/
LinkedIn – Group for Discussions & Questions: https://www.linkedin.com/groups/12555223/
Twitter: https://twitter.com/JoachimSchork

Music by bensound.com

Take the opportunity to connect and share this video with your friends and family if you find it useful.

Keywords: statisticsglobe.com, statistical programming, python programming, statistics, python programming language, python statistics, jupyter notebook, python language, python tutorial, learn python, python code, python programming tutorial, data science, data scientist, learn data science, Calculate Sum in Python (Examples), NumPy & pandas, List Object, One Particular Column & by Group

Read Also

Leave a Reply

Your email address will not be published. Required fields are marked *