pythonlines-of-code

Calculating the average of a specific row with loc, loc is not finding the row value


I'm new to Python and stackoverflow. So please forgive any shortcomings in my posting. I want to calculate the row average of a specific row(e.g. Bahrain) and I'm having problem achieving it. I used df.loc but It's returning a key error with the name of the country as it doesn't recognize the name. My dataframe look like something like this:

    Country   1990  1995 2000 2005 2010 2015
0   Bahrain     5     4    3    2   1    5
1   Maldives   10     9    8    7   6    5
2   Germany    7      4    3    2   1    7
.      ....     ..    ..   ..    ..  ..  ..
.      ....     ..    ..   ..    ..  ..  ..
.      ....     ..    ..   ..    ..  ..  ..

I wrote this and I get an error.I got a key error with the name of row.

mean=df.loc['Bahrain'].mean(axis=1)

I am getting the following error:

The error

I prefer to have an output in format of numpy.float64.


Solution

  • You need to specify the Bahrain at the df["Country"]. And also, you cannot mix text with numbers and take average. Here is how you can do it:

    rowAverage = df[df['Country'] == 'Bahrain'].iloc[:, 1:].mean()