按星期几分组 pandas [英] grouping by day of the week pandas

查看:84
本文介绍了按星期几分组 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  I have a dataframe,df 

        Index       eventName Count   pct
     2017-08-09       ABC     24     95.00%
     2017-08-09       CDE    140     98.50%
     2017-08-10       DEF    200     50.00%
     2017-08-11       CDE    150     99.30%
     2017-08-11       CDE    150     99.30%
     2017-08-16       DEF    200     50.00%
     2017-08-17       DEF    200     50.00%

我想通过对pct列中的值进行计数,按每日每周发生次数进行分组.例如,我们现在有:

I want to group by daily weekly occurrence by counting the values in the column pct. for example, we now have:

 2017-08-09 has 2 values in pct column  and  2017-08-16 has 1 value in pct, then we have Monday:3 
  2017-08-10  has 1 value and 2017-08-17 has 1 value,then we have Tuesday:2 and so on

然后,结果数据框应如下所示:

then the resulting dataframe should look like this:

    Index        Count   
 Monday            3
 Tuesday           2
 Wednesday         2

我尝试了df2=df.groupby(pd.Grouper(freq='D')).size().sort_values(ascending=False) 但它不是按星期几分组,也不会转换为单词的日期索引

I have tried df2=df.groupby(pd.Grouper(freq='D')).size().sort_values(ascending=False) but its not grouping by day of the week and not transforming to the date index to words

推荐答案

Wen对value_counts的回答很好,但没有考虑pct列中NaN的可能性.

Wen's answer with value_counts is good, but does not account for the possibility of NaNs in the pct column.

假设Index是索引,则可以调用groupby + count-

Assuming Index is the index, you can call groupby + count -

df.index = pd.to_datetime(df.index)
df.groupby(df.index.weekday_name).pct.count()

Index
Friday       2
Thursday     2
Wednesday    3
Name: pct, dtype: int64

要在工作日进行排序,请转换为pd.Categorical,如此处所示.

To sort on weekday, convert to pd.Categorical, as shown here.

这篇关于按星期几分组 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆