Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 namesdataSheet = 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.pyplotas plt
df[2010].plot(kind='bar', figsize=[30,10])

Histogram of 2010

Post a Comment for "How To Create Histograms In Panda Python Using Specific Rows And Columns In Data Frame"