繁体   English   中英

Pandas 的 groupby 不处理 agg 函数中的分类列

[英]Pandas' groupby doesn't process categoritcal columns in agg function

我有一个包含 3 列的数据框,两列是分类数据,一列是 float16。 当我执行 groupby 并在 agg 中运行特定于 lambda 的函数以根据 dtype 以不同方式处理每一列时,分类列上有一个下降。

如果这样做,它确实有效。

i=pd.DataFrame({"A":["a","a","a","b","c","c"],"B":[1,2,3,4,5,6],"C":[ "NaN" ,"b","NaN","b","c","c"]})
i['A'] = i['A'].astype('category')   
i['B'] = i['B'].astype('float16')   
i.groupby("A", as_index=False)[["B","C"]].agg(lambda x: x.mean() if np.dtype(x)=='float16' else x.value_counts().index[0])

我想要得到的输出是:

    A   B   C
0   a   2.0 NaN
1   b   4.0 b
2   c   5.5 c

但是,每当我将 C 列声明为分类时,python 都会自动删除 C 列。

i=pd.DataFrame({"A":["a","a","a","b","c","c"],"B":[1,2,3,4,5,6],"C":[ "NaN" ,"b","NaN","b","c","c"]})
i['A'] = i['A'].astype('category')   
i['B'] = i['B'].astype('float16')   
i['C'] = i['C'].astype('category')  
i.groupby("A", as_index=False)[["B","C"]].agg(lambda x: x.mean() if np.dtype(x)=='float16' else x.value_counts().index[0])

答案如下:

['C'] did not aggregate successfully. If any error is raised this will raise in a future version of pandas. Drop these columns/ops to avoid this warning.

A   B
0   a   2.0
1   b   4.0
2   c   5.5

有谁知道 groupby 的 agg 是否无法处理分类列?

categorypandas数据类型。 numpy不一定能很好地使用它( np.dtype(iC)给出错误)。 使用pandas.Series.dtype它应该可以按预期工作。

foo = lambda x: x.mean() if x.dtype =='float16' else x.value_counts().index[0]
i.groupby("A", as_index=False)[["B","C"]].agg(foo)
#    A    B    C
# 0  a  2.0  NaN
# 1  b  4.0    b
# 2  c  5.5    c

请注意,您没有正确检索类型:

i.groupby("A", as_index=False)[["B","C"]].agg(lambda x: print(np.dtype(x)))

给出“无”,而是使用x.dtype=='float16'因为xpd.Series 您可以检查.agg(lambda x: print(type(x)))

i['A'] = i['A'].astype('category')   
i['B'] = i['B'].astype('float16')   
i['C'] = i['C'].astype('category')
i.groupby("A", as_index=False)[["B","C"]].agg(lambda x: x.mean() if x.dtype=='float16' else x.value_counts().index[0])

给出:

    A   B   C
0   a   2.0 NaN
1   b   4.0 b
2   c   5.5 c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM