Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Summing all the rows of a Pandas Dataframe
To sum all the rows of a DataFrame, use the sum() function with axis=1. Setting the axis parameter to 1 adds values across columns for each row, while axis=0 (default) would sum down columns.
Creating a Sample DataFrame
Let's start by creating a DataFrame with stock data ?
import pandas as pd
dataFrame = pd.DataFrame({
"Opening_Stock": [300, 700, 1200, 1500],
"Closing_Stock": [200, 500, 1000, 900]
})
print("DataFrame...")
print(dataFrame)
DataFrame... Opening_Stock Closing_Stock 0 300 200 1 700 500 2 1200 1000 3 1500 900
Summing Rows with axis=1
Use sum(axis=1) to add values across columns for each row ?
import pandas as pd
dataFrame = pd.DataFrame({
"Opening_Stock": [300, 700, 1200, 1500],
"Closing_Stock": [200, 500, 1000, 900]
})
# Finding sum of row values
row_sums = dataFrame.sum(axis=1)
print("Summing rows...")
print(row_sums)
Summing rows... 0 500 1 1200 2 2200 3 2400 dtype: int64
Adding Row Sum as a New Column
You can also add the row sums as a new column to the original DataFrame ?
import pandas as pd
dataFrame = pd.DataFrame({
"Opening_Stock": [300, 700, 1200, 1500],
"Closing_Stock": [200, 500, 1000, 900]
})
# Add row sums as a new column
dataFrame['Total_Stock'] = dataFrame.sum(axis=1)
print(dataFrame)
Opening_Stock Closing_Stock Total_Stock 0 300 200 500 1 700 500 1200 2 1200 1000 2200 3 1500 900 2400
Key Points
-
axis=1sums across columns (row-wise) -
axis=0sums down rows (column-wise) - The result is a pandas Series with row sums
- You can assign the result to a new column
Conclusion
Use dataFrame.sum(axis=1) to sum all values across columns for each row. This returns a Series containing the sum of each row, which can be used for analysis or added back to the DataFrame.
Advertisements
