How to take mean across row in Pandas pivot table Dataframe?

Viewed 677

I have a pandas dataframe as seen below which is a pivot table. I would like to print Africa in 2007 as well as do the mean of the entire Americas row; any ideas how to do this? I have been doing combinations of stack/unstack for a while now to no avail.

year      1952  1957    1962    1967    1972    1977    1982    1987    1992    1997    2002    2007
continent                                               
Africa      12    13      15      20      39      25      81      12      22      23      25      44 
Americas    12    14      65      10     119      15      21      42      47      84      15      89
Asia        12    13      89      20      39      25      81      29      77      23      25      89
Europe      12    13      15      20      39      25      81      29      23      32      15      89
Oceania     12    13      15      20      39      25      81      27      32      85      25      89
1 Answers
import pandas as pd

df = pd.read_csv('dummy_data.csv')

# handy to see the continent name against the value rather than '0' or '3'
df.set_index('continent', inplace=True)

# print mean for all rows - see how the continent name helps here
print(df.mean(axis=1))
print('---')
print()

# print the mean for just the 'Americas' row
print(df.mean(axis=1)['Americas'])
print('---')
print()

# print the value of the 'Africa' row for the year (column) 2007
print(df.query('continent == "Africa"')['2007'])
print('---')
print()

Output:

continent
Africa      27.583333
Americas    44.416667
Asia        43.500000
Europe      32.750000
Oceania     38.583333
dtype: float64
---

44.416666666666664
---

continent
Africa    44
Name: 2007, dtype: int64
---
Related