我是 pandas/Numpy 的新手,我正在尝试看看一切如何运作。
我将此数据集用于 IMDb 电影评分前 1000 名: https://github.com/justmarkham/pandas-videos/blob/master/data/imdb_1000.csv
我正在尝试按流派分组,按电影数量(> 100)过滤,然后显示最小值/最大值/平均值(作为整数)/中值(作为整数)/计数。
到目前为止我有:
df.groupby("genre")['duration'].aggregate(['min', max, np.mean, np.median, 'count']).sort_values('median', ascending=False)
这显示了所有流派和时长统计数据,但均值和中位数是 float ,并且它包括那些计数较低的。
我想以某种方式将它与这样的东西结合起来:
df.groupby("genre")['duration'].filter(lambda x: x.count() > 100)
和
df.groupby("genre")['duration'].mean().astype(int)
这可能吗?
接下来,我想将其绘制成图表,但那是另一天的事......
谢谢!
编辑 1
为了澄清,目前我得到:
genre min max mean median count
Western 85 175 136.666667 135.0 9
Adventure 89 224 134.840000 127.0 75
Biography 85 202 131.844156 127.0 77
Action 80 205 126.485294 125.0 136
Drama 64 242 126.539568 123.0 278
Crime 67 229 122.298387 118.0 124
Thriller 107 120 114.200000 116.0 5
Mystery 69 160 115.625000 115.0 16
Sci-Fi 91 132 109.000000 113.0 5
Fantasy 112 112 112.000000 112.0 1
Family 100 115 107.500000 107.5 2
Comedy 68 187 107.602564 104.0 156
Horror 70 146 102.517241 104.0 29
Animation 75 134 96.596774 94.5 62
Film-Noir 88 111 97.333333 93.0 3
History 66 66 66.000000 66.0 1
但是我想要:
genre min max mean median count
Action 80 205 126 125 136
Drama 64 242 127 123 278
Crime 67 229 122 118 124
Comedy 68 187 108 104 156
最佳答案
是,您可以简单地链接过滤器和groupby
:
df.groupby('genre').filter(
lambda x: len(x) > 100
).groupby('genre')['duration'].aggregate(
['min','max','mean','median','count']
).sort_values('median', ascending=False)
结果如下:
>>> df.groupby('genre').filter(lambda x: len(x) > 100).groupby('genre')['duration'].aggregate(['min','max','mean','median','count']).sort_values('median', ascending=False)
min max mean median count
genre
Action 80 205 126.485294 125 136
Drama 64 242 126.539568 123 278
Crime 67 229 122.298387 118 124
Comedy 68 187 107.602564 104 156
您也可以将其转换为整数:
>>> df.groupby('genre').filter(lambda x: len(x) > 100).groupby('genre')['duration'].aggregate(['min','max','mean','median','count']).sort_values('median', ascending=False).astype(int)
min max mean median count
genre
Action 80 205 126 125 136
Drama 64 242 126 123 278
Crime 67 229 122 118 124
Comedy 68 187 107 104 156
关于python - Pandas/Numpy Groupby + 聚合(包括整数均值)+ 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132343/