本文介绍了Pandas 'count(distinct)' 等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Pandas 作为数据库替代品,因为我有多个数据库(Oracle、SQL Server 等),并且我无法对 SQL 等效项生成一系列命令.
I am using Pandas as a database substitute as I have multiple databases (Oracle, SQL Server, etc.), and I am unable to make a sequence of commands to a SQL equivalent.
我在 DataFrame 中加载了一个表,其中包含一些列:
I have a table loaded in a DataFrame with some columns:
YEARMONTH, CLIENTCODE, SIZE, etc., etc.
在 SQL 中,计算每年不同客户的数量是:
In SQL, to count the amount of different clients per year would be:
SELECT count(distinct CLIENTCODE) FROM table GROUP BY YEARMONTH;
结果是
201301 5000
201302 13245
我怎样才能在 Pandas 中做到这一点?
How can I do that in Pandas?
推荐答案
我相信这就是你想要的:
I believe this is what you want:
table.groupby('YEARMONTH').CLIENTCODE.nunique()
示例:
In [2]: table
Out[2]:
CLIENTCODE YEARMONTH
0 1 201301
1 1 201301
2 2 201301
3 1 201302
4 2 201302
5 2 201302
6 3 201302
In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]:
YEARMONTH
201301 2
201302 3
这篇关于Pandas 'count(distinct)' 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!