in pandas how can I groupby weekday() for a datetime column?

前端 未结 2 1389
不知归路
不知归路 2021-02-01 22:37

I\'d like to filter out weekend data and only look at data for weekdays (mon(0)-fri(4)). I\'m new to pandas, what\'s the best way to accomplish this in pandas?

         


        
相关标签:
2条回答
  • 2021-02-01 22:49

    your call to the function "weekday" does not work as it operates on the index of data.my_dt, which is an int64 array (this is where the error message comes from)

    you could create a new column in data containing the weekdays using something like:

    data['weekday'] = data['my_dt'].apply(lambda x: x.weekday())
    

    then you can filter for weekdays with:

    weekdays_only = data[data['weekday'] < 5 ]
    

    I hope this helps

    0 讨论(0)
  • 2021-02-01 22:52

    Faster way would be to use DatetimeIndex.weekday, like so:

    temp = pd.DatetimeIndex(data['my_dt'])
    data['weekday'] = temp.weekday
    

    Much much faster, especially for a large number of rows. For further info, check this answer.

    0 讨论(0)
提交回复
热议问题