how to get the mean of a dataframe with multi index?

Question:

I am trying to get the mean of each column for one value. That value is repeated in the multi index. For consideration I am giving one example.

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'A': ['A', 'A', 'A','B', 'B', 'B'],
                   'B': ['2000','2001','2002','2000','2001','2002'],
                   'C': [1, 2, 3, 4, 5, 6],
                   'D': [4, 5, 6, 7, 8, 9]})

# set the columns A and B as the multi-index
df = df.set_index(['A', 'B'])

Lets say the A column is the Country column, and B column is the year. C and D are different values. There are 2 countries. What I want is a df that have de year as the index, and in the column C and D the mean value of that year for the 2 countries.

This is the desired df

desired_df = pd.DataFrame({'B': ['2000','2001','2002'],
                   'C': [2.5, 3.5, 4.5],
                   'D': [5.5, 6.5, 7.5]})

And this is what Ive done

desired_df=df.pivot_table(values=df.columns, index='B', aggfunc='mean')

I don’t know if it is working, what I know for sure is that with my data, columns are not in the same order.

For reproducibility, this is the code, df_resto will be the desired_df

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import wbdata as wb
from sklearn.linear_model import LinearRegression
from textwrap import wrap

country = ['CHN','DEU','USA','KOR','JPN']


indicators={'SE.TER.ENRR' : 'Inscripción escolar, nivel terciario (% bruto)','SP.URB.TOTL.IN.ZS' : 'Población urbana (% del total)',
           'IP.JRN.ARTC.SC' : 'Artículos en publicaciones científicas y técnicas', 'IP.PAT.RESD' : 'Solicitudes de patentes, residentes',
           'GB.XPD.RSDV.GD.ZS' : 'Gasto en investigación y desarrollo (% del PIB)', 'BM.KLT.DINV.WD.GD.ZS' : 'Inversión extranjera directa, salida neta de capital (% del PIB)',
           'TX.VAL.TECH.MF.ZS' : 'Exportaciones de productos de alta tecnología (% de las exportaciones de productos manufacturados)',
           'NV.MNF.TECH.ZS.UN' : 'Valor añadido de la industria manufacturera de media y alta tecnología (% de valor añadido de la industria manufacturera)',
           'NV.IND.TOTL.ZS' : 'Industria, valor agregado (% del PIB)','SP.POP.TOTL':'Población'}

df=wb.get_dataframe(indicators, country = country)
df=df.sort_index()

df['Artículos en publicaciones científicas per cápita']=df['Artículos en publicaciones científicas y técnicas']/df['Población']
df['Solicitudes de patentes per cápita']=df['Solicitudes de patentes, residentes']/df['Población']

df_china = df[df.index.isin(['China'], level=0)]
df_china = df_china.reset_index()

df_china=df_china.set_index('date')

valores =['Inscripción escolar, nivel terciario (% bruto)',
       'Población urbana (% del total)',
       'Gasto en investigación y desarrollo (% del PIB)',
       'Inversión extranjera directa, salida neta de capital (% del PIB)',
       'Exportaciones de productos de alta tecnología (% de las exportaciones de productos manufacturados)',
       'Valor añadido de la industria manufacturera de media y alta tecnología (% de valor añadido de la industria manufacturera)',
       'Industria, valor agregado (% del PIB)',
       'Artículos en publicaciones científicas per cápita',
       'Solicitudes de patentes per cápita']

df_china=df_china[valores]

df_resto = df[df.index.isin(['United States','Germany','Japan','Korea, Rep.'], level=0)]
df_resto = df_resto.reset_index()
df_resto=df_resto.set_index('date')
df_resto = df_resto[valores]

df_resto=df_resto.pivot_table(values=valores, index='date', aggfunc='mean')

Answers:

df.groupby(level=1).mean().reset_index()

result

    B       C   D
0   2000    2.5 5.5
1   2001    3.5 6.5
2   2002    4.5 7.5
Answered By: Panda Kim
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.