我有一个包含超过 150.000 条电视节目数据记录、数十个 channel 的数据集,但并非所有 channel 都有全天的数据。
我想按 channel 、年份和月份对它们进行分组,统计每个月有多少天有每个 channel 的记录。
这里是数据框的一小部分
df = pd.DataFrame(
{"channel": {"631": "CBR", "632": "CBR", "633": "CBR"}, "year": {"631": "2014", "632": "2014", "633": "2014"},
"month": {"631": "01", "632": "01", "633": "01"}, "day": {"631": "06", "632": "06", "633": "06"},
"t1": {"631": 1388967300000, "632": 1388973300000, "633": 1388974500000},
"title": {"631": "title 1", "632": "title 2", "633": "title 3"}})
我用这种方式试过groupby
grouped = df.groupby(['channel', 'year','month', 'day']).count().reset_index()
所以我在第 12 个月得到了一个 channel 的结果。
但我想要的是计算每个月每个 channel 存在多少个不同的天数。
对于上面的例子我会有
全职培训 | 2014 | 12 | 31
我正在使用 python 3.5.2 和 Pandas 0.19.1。
感谢任何建议。
请您参考如下方法:
你可以试试这个:
In [110]: df.groupby(['channel','year','month'])['day'].apply(lambda x: len(x.unique()))
Out[110]:
channel year month
CBR 2014 01 1
Name: day, dtype: int64
或者,按照@MaxU 和@TedPetrou 的建议,您可以使用 .nunique(),如下所示:
In [5]: df.groupby(['channel','year','month'])['day'].nunique()
Out[5]:
channel year month
CBR 2014 01 1
Name: day, dtype: int64
nunique() 似乎是性能方面的明智选择,见下文:
In [6]: %timeit df.groupby(['channel','year','month'])['day'].apply(lambda x: len(x.unique()))
The slowest run took 4.39 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 4.42 ms per loop
In [7]: %timeit df.groupby(['channel','year','month'])['day'].nunique()
100 loops, best of 3: 2.05 ms per loop
