我是Pandas / Numpy的新手,我在玩耍以查看一切工作原理。
我将这个数据集用于前1000个IMDb电影评分: 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)
这显示了所有流派和持续时间统计信息,但均值和中位数是浮点数,其中包括计数较低的那些。
我想以某种方式将其与以下内容结合起来:
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
答案 0 :(得分:3)
是,您只需链接过滤器和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
答案 1 :(得分:2)
由于数据集相对较小,因此运行计算并在此之后进行过滤不会造成损害。
file = 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv'
data = (pd.read_csv(file)
.groupby("genre")['duration']
.agg(['min', 'max', 'mean', 'median', 'count'])
.loc[lambda x:x['count']>100]
.sort_values('median', ascending=False))
loc
具有lambda函数,是一种无需创建中间变量即可更轻松地过滤列的方法。