使用Lambda函数进行分组和聚合 [英] Groupby and aggregate using lambda functions

查看:101
本文介绍了使用Lambda函数进行分组和聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以编程方式创建的lambda函数对数据帧进行分组汇总.这样一来,我可以模拟一列中存在的类别的一键式编码器.

I am trying to groupby-aggregate a dataframe using lambda functions that are being created programatically. This so I can simulate a one-hot encoder of the categories present in a column.

数据框:

df = pd.DataFrame(np.array([[10, 'A'], [10, 'B'], [20, 'A'],[30,'B']]),
                   columns=['ID', 'category'])

ID category
10 A
10 B
20 A
30 B

预期结果:

ID A B
10 1 1
20 1 0
30 0 1

我正在尝试:

one_hot_columns = ['A','B']
lambdas = [lambda x: 1 if x.eq(column).any() else 0 for column in one_hot_columns]
df_g = df.groupby('ID').category.agg(lambdas)

结果:

ID A B
10 1 1
20 0 0
30 1 1

但是以上内容并不是预期的结果.不知道我在做什么错.我知道我可以使用get_dummies做到这一点,但是使用lambdas可以更方便地实现自动化.另外,我可以确保输出列的顺序.

But the above is not quite the expected result. Not sure what I am doing wrong. I know I could do this with get_dummies, but using lambdas is more convenient for automation. Also, I can ensure the order of the output columns.

推荐答案

使用交叉表:

pd.crosstab(df.ID, df['category']).reset_index()

输出:

category  ID  A  B
0         10  1  1
1         20  1  0
2         30  0  1

这篇关于使用Lambda函数进行分组和聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆