Shan Khan Shan Khan - 2 days ago 5
Python Question

How to create Histograms in Panda Python Using Specific Rows and Columns in Data Frame

I have the following data frame in the picture, i want to take a Plot a histogram to show the distribution of all countries in the world for any given year (e.g. 2010).

Following is my code table generates after the following code of cleaning:

dataSheet = pd.read_excel("http://api.worldbank.org/v2/en/indicator/EN.ATM.CO2E.PC?downloadformat=excel",sheetname="Data")
dataSheet = dataSheet.transpose()
dataSheet = dataSheet.drop(dataSheet.columns[[0,1]], axis=1) ;
dataSheet = dataSheet.drop(['World Development Indicators', 'Unnamed: 2','Unnamed: 3'])


enter image description here

Answer

In order to plot a histogram of all countries for any given year (e.g. 2010), I would do the following. After your code:

dataSheet = pd.read_excel("http://api.worldbank.org/v2/en/indicator/EN.ATM.CO2E.PC?    downloadformat=excel",sheetname="Data")
dataSheet = dataSheet.transpose()
dataSheet = dataSheet.drop(dataSheet.columns[[0,1]], axis=1)
dataSheet = dataSheet.drop(['World Development Indicators', 'Unnamed: 2','Unnamed: 3'])

I would reorganise the column names, by assigning the actual country names as column names:

dataSheet.columns = dataSheet.iloc[1] # here I'm assigning the column names
dataSheet = dataSheet.reindex(dataSheet.index.drop('Data Source')) # here I'm re-indexing and getting rid of the duplicate row

Then I would transpose the data frame again (to be safe I'm assigning it to a new variable):

df = dataSheet.transpose()

And then I'd do the same as I did before with assigning new column names, so we get a decent data frame (although still not optimal) with country names as index.

df.columns = df.iloc[0]
df = df.reindex(df.index.drop('Country Name'))

Reorganised dataframe

Now you can finally plot the histogram for e.g. year 2010:

import matplotlib.pyplot as plt
df[2010].plot(kind='bar', figsize=[30,10])

Histogram of 2010

Comments