【问题标题】:How many days have a dataset has records per each month in a pandas dataframe?熊猫数据框中每个月有多少天的数据集有记录?
【发布时间】:2016-12-12 06:55:47
【问题描述】:

我有一个数据集,其中包含超过 150,000 条电视节目数据记录、数十个频道,但并非所有频道都有整天的数据。

我想按频道、年份和月份对它们进行分组,计算每个频道每个月有多少天有记录。

这里是一小块数据框

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"}})

我试过用这种方式分组

grouped = df.groupby(['channel', 'year','month', 'day']).count().reset_index()

所以我在第 12 个月得到了一个频道的这个结果。

但我想要计算每个月每个频道存在多少天。

对于上面的示例,我将有

WBT | 2014 | 12 | 31

我正在使用 python 3.5.2 和 Pandas 0.19.1。

感谢您的任何建议。

【问题讨论】:

  • 这就是你想要的:df.groupby(['channel', 'year','month'])['day'].nunique().reset_index()
  • 感谢@MaxU,它正是我所需要的。

标签: python pandas dataframe


【解决方案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

【讨论】:

  • 有一个直接的调度方法nunique,不需要apply。查看@MaxU 的评论
【解决方案2】:
# not add 'day' in groupby 
bydays = df.groupby(['channel','year','month'])

print(bydays['day'].count())

【讨论】:

  • 谢谢@Danil.V,我试过了,但是这样做我得到的是一个月内每天的记录总数,而不是一个月有多少天有记录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 2017-03-24
  • 1970-01-01
  • 2021-06-02
  • 2018-08-14
  • 1970-01-01
  • 2016-09-06
相关资源
最近更新 更多