gpt4 book ai didi

python - 使用 Nan 值计算最频繁的组

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:03 25 4
gpt4 key购买 nike

基本上我想计算按 2 个变量分组的最频繁项目的数量。我使用这段代码:

dfgrouped = data[COLUMNS.copy()].groupby(['Var1','Var2']).agg(lambda x: stats.mode(x)[1])

此代码有效,但不适用于具有 Nan 值的列,因为 NaN 值为 float 而其他值为 str。因此显示此错误:

'<' not supported between instances of 'float' and 'str'

我想省略 NaN 值和其余的计数模式。所以 str(x) 不是解决方案。并且 scipy.stats.mode(x, nan_policy='omit') 既不工作也没有错误:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

你能给我一个建议如何处理这个问题吗?谢谢

最佳答案

我认为需要dropna用于删除 NaN:

dfgrouped = data[COLUMNS.copy()].groupby(['Var1','Var2']).agg(lambda x: stats.mode(x.dropna())[1])

如果需要为所有 NaN 组设置 NaN:

dfgrouped = (data[COLUMNS.copy()]
.groupby(['Var1','Var2'])
.agg(lambda x: None if x.isnull().all() else stats.mode(x.dropna())[1]))

关于python - 使用 Nan 值计算最频繁的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51132161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com