在Python中使用每个单元格中的数值平均值制作双向表

时间:2017-11-21 03:45:18

标签: python pandas

我有不同种族,不同性别和不同年份的预期寿命数据。现在我需要根据所有年份的种族和性别制作一个双向平均预期寿命表。

life_sex_race = pd.pivot_table(data, values=['Life'], index=['Sex'], columns=['Race'], aggfunc=[np.mean])

然而,它一直给我错误:

No numeric types to aggregate

Life.dtypes显示为'float64'。我不确定为什么会这样。

1 个答案:

答案 0 :(得分:0)

我拿了一个样本数据框,然后试了一下

import pandas as pd
import numpy as np

df = pd.DataFrame({"Race": ["humans", "humans", "humans", "humans", "humans", "mammals", "mammals", "mammals", "mammals"],
                "Sex": ["F", "F", "F", "M", "M", "F", "F", "M", "M"],
               "year": ["1980", "1982", "1990", "1980", "1987", "1990", "1980", "1992","1990"],
              "Life": [67.0, 18.5, 25.7, 73.009, 30.9, 45.555, 85.5, 60.009, 97.6]})

table = pd.pivot_table(df, columns=['Race'], index=['Sex','year'], values=['Life'], aggfunc=np.mean)

print table

以下是输出:

            Life        
Race      humans mammals
Sex year                
F   1980  67.000  85.500
    1982  18.500     NaN
    1990  25.700  45.555
M   1980  73.009     NaN
    1987  30.900     NaN
    1990     NaN  97.600
    1992     NaN  60.009