1

I have a pandas dataframe, in which a column is a string formatted as

yyyymmdd

which should be a date. Is there an easy way to convert it to a recognizable form of date?

And then what python libraries should I use to handle them? Let's say, for example, that I would like to consider all the events (rows) whose date field is a working day (so mon-fri). What is the smoothest way to handle such a task?

sato
  • 768
  • 1
  • 9
  • 30
  • I was confused. You should have used dayofweek instead of day. Try it. – Anton vBR Jun 11 '18 at 14:45
  • `dayofweek` works! Only one thing, days are numbered 0-6, so it should be `m= pd.to_datetime(df['date']).dt.dayofweek < 5 ` if you want to select mon-friday. Edit your answer so that I can pick it as correct, and thanks a lot :) – sato Jun 11 '18 at 15:01
  • It is done.... :=) – Anton vBR Jun 11 '18 at 15:53

1 Answers1

2

Ok so you want to select Mon-Friday. Do that by converting your column to datetime and check if the dt.dayofweek is lower than 6 (Mon-Friday --> 0-4)

m = pd.to_datetime(df['date']).dt.dayofweek < 5
df2 = df[m]

Full example:

import pandas as pd

df = pd.DataFrame({
    'date': [
        '20180101',
        '20180102',
        '20180103',
        '20180104',
        '20180105',
        '20180106',
        '20180107'
    ],
    'value': range(7)
})

m = pd.to_datetime(df['date']).dt.dayofweek < 5

df2 = df[m]
print(df2)

Returns:

       date  value
0  20180101      0
1  20180102      1
2  20180103      2
3  20180104      3
4  20180105      4
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • Actually. Yearfirst is more for dates like: `08/10/08`. The format is not needed. – Anton vBR Jun 11 '18 at 12:39
  • Not sure why it's not working if I pick days beyond the 9th of each month. To reproduce it: `df= pd.DataFrame({ 'date': [ '20180124', '20180123', '20180112', '20180115', '20180121', '20180102', '20180101' ] })` – sato Jun 11 '18 at 14:16
  • After further attempts, maybe that's not the cause. By the way it's still not working on a sample different from the one you provided, I can't figure out why. – sato Jun 11 '18 at 14:23
  • I can have a look later. – Anton vBR Jun 11 '18 at 14:43