Home > OS >  How To Subtract Values In Columns Using MatplotLib and Pandas and Display Them
How To Subtract Values In Columns Using MatplotLib and Pandas and Display Them

Time:12-23

I am working with a program that uses a .csv file similar to the following data.

Country,Year,Life expectancy at birth (years),Healthy Life expectancy at birth (years)
Afghanistan,2019,63.2,53.9
Afghanistan,2015,61.7,52.6
Afghanistan,2010,59.9,51.1
Afghanistan,2000,55,46.8
Albania,2019,78,69.1
Albania,2015,77.8,69
Albania,2010,76.2,67.6
Albania,2000,73.5,65.2
Algeria,2019,77.1,66.4
Algeria,2015,76.5,66
Algeria,2010,75.9,65.5
Algeria,2000,72.2,62.7
Angola,2019,63.1,54.8
Angola,2015,61.7,53.7
Angola,2010,58.1,50.6
Angola,2000,49.3,42.9

I want to write a program that subtracts the life expectancy for each country in 2000 from the life expectancy for each country at 2019. How would I got about doing that? For example for Afghanistan I would want to do 63.2 - 55 and display that on a graph with Afghanistan on the x-axis.

CodePudding user response:

You could group by country and write a simple aggregation function fitting the specific needs.

By doing so you get a new dataframe with index country and delta_livespan as column

CodePudding user response:

This does it, although there may be a better way. With pandas, there usually is.

import pandas as pd


df = pd.read_csv('x.csv')
c2 = df.columns[2]
print(df)
df2019 = df[(df['Year']==2019)].set_index('Country')
df2000 = df[(df['Year']==2000)].set_index('Country')
df2019['increase'] = df2019[c2]-df2000[c2]
print(df2019)
  • Related