snehal pimpare
snehal pimpare

Reputation: 43

Hi, I am trying to add weekstart column

In my current table I am having date column and from that column I am able to find out weekday.By using to_timedelta I have created week_start column but it is not giving correct date. Here the code is:

final_data['weekday'] = final_data['DateOfInvoice'].dt.weekday

final_data['Weekstart'] = final_data['DateOfInvoice'] - pd.to_timedelta(final_data['weekday'],unit='ns', box=True, coerce=True)

output is as:

 Date       weekday   weekstart
2016-07-23  5         2016-07-22

Upvotes: 1

Views: 53

Answers (1)

EdChum
EdChum

Reputation: 394003

IIUC you can construct a TimedeltaIndex and subtract from the other column:

In [152]:
df['weekstart'] = df['Date'] - pd.TimedeltaIndex(df['weekday'], unit='D')
df

Out[152]:
        Date  weekday  weekstart
0 2016-07-23        5 2016-07-18

in fact the weekday column is unnecessary:

In [153]:
df['weekstart'] = df['Date'] - pd.TimedeltaIndex(df['Date'].dt.dayofweek, unit='D')
df

Out[153]:
        Date  weekday  weekstart
0 2016-07-23        5 2016-07-18

Upvotes: 1

Related Questions