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
Write a program in Python to read CSV data from a file and print the total sum of last two rows
When working with CSV files in Python, you often need to perform calculations on specific rows. This tutorial shows three different methods to read CSV data and calculate the sum of the last two rows using pandas.
Sample CSV Data
First, let's create a sample CSV file named pandas.csv:
Id,Data 1,11 2,22 3,33 4,44 5,55 6,66 7,77 8,88 9,99 10,100
Using tail() Method
The tail() method returns the last n rows of a DataFrame. Combined with sum(), it provides a clean solution ?
import pandas as pd
# Read CSV file
data = pd.read_csv('pandas.csv')
df = pd.DataFrame(data)
print("DataFrame is:")
print(df)
print("\nSum of last two rows:")
print(df.tail(2).sum())
DataFrame is: Id Data 0 1 11 1 2 22 2 3 33 3 4 44 4 5 55 5 6 66 6 7 77 7 8 88 8 9 99 9 10 100 Sum of last two rows: Id 19 Data 199 dtype: int64
Using iloc Indexing
The iloc[-2:] slice selects the last two rows using negative indexing ?
import pandas as pd
# Read CSV file
data = pd.read_csv('pandas.csv')
df = pd.DataFrame(data)
print("DataFrame is:")
print(df)
print("\nSum of last two rows:")
print(df.iloc[-2:].sum())
DataFrame is: Id Data 0 1 11 1 2 22 2 3 33 3 4 44 4 5 55 5 6 66 6 7 77 7 8 88 8 9 99 9 10 100 Sum of last two rows: Id 19 Data 199 dtype: int64
Using Loop with Conditional Logic
This manual approach iterates through the DataFrame and identifies the last two rows ?
import pandas as pd
# Read CSV file
data = pd.read_csv('pandas.csv')
df = pd.DataFrame(data)
id_sum = 0
data_sum = 0
for i in range(len(df)):
if i == len(df) - 2 or i == len(df) - 1:
id_sum = id_sum + df.iloc[i][0]
data_sum = data_sum + df.iloc[i][1]
print("Id:", id_sum)
print("Data:", data_sum)
Id: 19 Data: 199
Comparison
| Method | Code Length | Readability | Best For |
|---|---|---|---|
tail() |
Short | High | Simple sum calculations |
iloc[-2:] |
Short | High | Slice-based operations |
| Loop method | Long | Medium | Complex conditional logic |
Conclusion
Use tail(2).sum() or iloc[-2:].sum() for simple summation tasks as they are more readable and efficient. The loop method is useful when you need custom logic for row processing.
