Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Postgres GROUP BY中唯一值的计数_Sql_Postgresql_Pandas - Fatal编程技术网

Sql Postgres GROUP BY中唯一值的计数

Sql Postgres GROUP BY中唯一值的计数,sql,postgresql,pandas,Sql,Postgresql,Pandas,我有一个带有模式的表: uid | day | type 在pandas中,它看起来像这样: d=pd.DataFrame(columns=['uid','day','type']) d.loc[0]=[1,1,'C'] d.loc[1]=[1,1,'T'] d.loc[2]=[1,1,'C'] d.loc[3]=[2,1,'T'] d.loc[4]=[1,2,'T'] 我想: 分组依据uid和日期 获取每组唯一类型值的计数 返回每组前3个类型值 在pandas中,可以获得每组的唯一值计

我有一个带有模式的表:

uid | day | type
pandas
中,它看起来像这样:

d=pd.DataFrame(columns=['uid','day','type'])
d.loc[0]=[1,1,'C']
d.loc[1]=[1,1,'T']
d.loc[2]=[1,1,'C']
d.loc[3]=[2,1,'T']
d.loc[4]=[1,2,'T']
我想:

  • 分组依据
    uid
    日期
  • 获取每组唯一
    类型
    值的计数
  • 返回每组前3个
    类型
pandas
中,可以获得每组的唯一值计数:

d.groupby(['uid','day']).type.value_counts()
输出(然后我将过滤以获得每组前3名)


postgres
中如何执行此查询?

我不确定是否完全理解您的问题,但由于我无法留下评论,我将尝试一下

假设表t包含以下数据:

 uid | day | type 
-----+-----+------
   1 |   1 | C
   1 |   1 | T
   1 |   1 | C
   2 |   1 | T
   1 |   2 | T
然后,此查询将返回您想要的内容:

  SELECT uid, day, type, count(type) 
  FROM t 
  GROUP BY uid, day, type;

 uid | day | type | type_count 
-----+-----+------+------------
   1 |   1 | C    |     2
   1 |   2 | T    |     1
   1 |   1 | T    |     1
   2 |   1 | T    |     1
然后,您可以通过DESC对列类型_count下订单,限制为3,您将获得前3名


我希望这就是您要找的。

您想要每个uid和每天的类型计数吗?将示例数据和预期输出添加到您的问题中。谢谢,刚刚这么做了。谢谢你的任何想法。谢谢,谢谢。这里的问题很简单:如何获取每个用户每天的评论类型频率?要点是,
postgres
似乎没有agg函数来计算组中项目的频率。所以,我想知道如何轻松地做到这一点。
  SELECT uid, day, type, count(type) 
  FROM t 
  GROUP BY uid, day, type;

 uid | day | type | type_count 
-----+-----+------+------------
   1 |   1 | C    |     2
   1 |   2 | T    |     1
   1 |   1 | T    |     1
   2 |   1 | T    |     1