简体   繁体   English

如何从熊猫数据框值中计算特定日期间隔内的值数?

[英]How to count number of values within specific date interval from pandas dataframe values?

I want to count and plot the number of 'payout' values by day for period 2018-04-01 to 2018-05-01 from this dataframe: 我想从此数据帧中按天数计算并绘制2018-04-01至2018-05-01期间的'支付'值的数量:

df['payout'].head(10)

0   2017-02-14 11:00:06
1   2015-03-14 11:00:06
2   2014-04-14 11:00:06
3   2017-11-14 11:00:06
4   2016-12-14 11:00:06
5   2018-04-10 11:00:06
6   2018-04-11 11:00:06
7   2018-04-12 11:00:06
8   2018-04-13 11:00:06
9   2018-04-14 11:00:06

I could obtain day-to-plot for the year 2018: 我可以获得2018年的日图:

(df.loc[df['payout'].dt.year.between(2018, 2019), 'payout']
         .dt.to_period('D')
         .value_counts()
         .sort_index()
         .plot(kind="bar")
)

在此处输入图片说明

How do I shrink the plot to April 2018 only? 我如何将地块缩小至2018年4月?

Thanks 谢谢

只需检查月份和年份并使用当前方法

df.loc[(df.date.dt.month == 4) & (df.date.dt.year == 2018), 'payout']

You could use the same logic you were using, but use the datestrings you are interested in: 您可以使用与您所使用的逻辑相同的逻辑,但可以使用您感兴趣的日期字符串:

(df.loc[df['payout'].between('2018-04-01', '2018-04-30'), 'payout']
         .dt.to_period('D')
         .value_counts()
         .sort_index()
         .plot(kind="bar")
)

另一种解决方案:

df[(df['date'] >= '2018-04-01') & (df['date'] < '2018-05-01')]['payout']
df.set_index('payout').loc['2018-04-01':'2018-04-30']

for your first line should do it. 您的第一行应该这样做。

  • .set_index makes your payout column the index. .set_index将您的支出列作为索引。 This does not modify the original df . 这不会修改原始df See the docs for details. 有关详细信息,请参阅文档
  • Now that you have a DatetimeIndex , you can just use .loc to index with date strings directly. 现在您有了DatetimeIndex ,您只需使用.loc即可直接为日期字符串建立索引。 Note that unlike normal indexing, this will include all 24 hours of April 30. 请注意,与正常索引编制不同的是,它将包括4月30日的所有24小时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM