Write a program in Python to read CSV data from a file and print the total sum of last two rows


Assume you have the following data in your csv file and save it as pandas.csv.

pandas.csv

Id,Data
1,11
2,22
3,33
4,44
5,55
6,66
7,77
8,88
9,99
10,100

The result for sum of last two records as,

Sum of last two rows:
Id    9
Data 99

Solution 1

  • Access stored data from csv file and save it as data using the below method,

data = pd.read_csv('pandas.csv')
  • Convert the data into dataframe and store inside df,

df = pd.DataFrame(data)
  • Apply the below method to take last two records and calculate the sum,

df.tail(2)).sum()

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
data = pd.read_csv('pandas.csv')
df = pd.DataFrame(data)
print("Dataframe is\n",df)
print("Last two rows\n",df.tail(2).sum())

Output

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
Last two rows
Id    19
Data 199

Solution 2

  • Access stored data from csv file and save it as data using the below method,

data = pd.read_csv('pandas.csv')
  • Convert the data into dataframe and store inside df,

df = pd.DataFrame(data)
  • Apply the below slicing index method to take last two records,

df.iloc[-2:]

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
data = pd.read_csv('pandas.csv')
df = pd.DataFrame(data)
print("Dataframe is\n",df)
print("Last two rows\n",df.iloc[-2:].sum())

Output

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
Last two rows
Id    19
Data 199

Solution 3

  • Access stored data from csv file and save it as data using the below method,

data = pd.read_csv('pandas.csv')
  • Convert the data into dataframe and store inside df,

df = pd.DataFrame(data)
  • Set id sum and data sum initial value as 0

  • Set a for loop to access dataframe data and set an if condition to access last two data,

for i in range(len(df)):
if(i==len(df)-2 or i==len(df)-1):
  • Calculate first and second column sum using df.iloc[i][0] and df.iloc[i][1],

id_sum = id_sum + df.iloc[i][0]
data_sum = data_sum + df.iloc[i][1]

Example

Let’s see the following implementation to get a better understanding,

import pandas as pd
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)

Output

Id    19
Data 199

Updated on: 24-Feb-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements