pandas.core.base.DataError: No numeric types to aggregate错误规避

我没有去解决这个问题, 而用填充0规避了这个问题

统计 聚合

d = [
    {'cur': 1, 'next': 2, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 3, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 4, 'avgtime': None, 'callcount': None},

    {'cur': 1, 'next': 2, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 3, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 4, 'avgtime': None, 'callcount': None},

    {'cur': None, 'next': 4, 'avgtime': None, 'callcount': None},
]

df = pd.DataFrame(d, dtype='int')
df.groupby(["cur", "next"], as_index=False).mean()

重要总结:

1. None为NaN
2. count会统计空字符串, 但是cont不统计NaN.  sum不统计NaN, 否则就会像sql里select(1+NULL)结果是NULL
3. 分组key为None时,记录不显示

计算mean()时DataError: No numeric types to aggregate

1312420-20190110110725727-348818367.png

1312420-20190110110803262-1742032078.png

agg函数

使用这种聚合会卡到这个bug
pandas.core.base.DataError: No numeric types to aggregate错误规避

import pandas as pd

d = [
    {'cur': 1, 'next': 2, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 3, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 4, 'avgtime': None, 'callcount': None},

    {'cur': 1, 'next': 2, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 3, 'avgtime': None, 'callcount': None},
    {'cur': 2, 'next': 4, 'avgtime': None, 'callcount': None},

    {'cur': None, 'next': 4, 'avgtime': None, 'callcount': None},
]

df = pd.DataFrame(d, dtype='int')
g = df.groupby(["cur", "next"], as_index=False)
res = g.agg(
    {
        'avgtime': 'sum',
        'callcount': 'mean',
    }
)

复杂的分组: cur分别与p1 p2 p3分组

import numpy as np
import pandas as pd

d = [
    {
        'cur': 1,
        'p1_next': 1,
        'p1_avgtime': 10,
        'p1_callaccount': 10,

        'p2_next': 2,
        'p2_avgtime': None,
        'p2_callaccount': 10,

        'p3_next': 3,
        'p3_avgtime': 10,
        'p3_callaccount': None,
    }
]

df = pd.DataFrame(d, dtype='int')
df.groupby(["cur", "p2_next"], as_index=False).sum().to_dict(orient='records')

1312420-20190110170815528-1007186089.png

转载于:https://www.cnblogs.com/iiiiiher/p/10218994.html

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐