I have the following df :
import pandas as pd
from datetime import datetime, timedelta
df = pd.DataFrame([
["A", "2018-08-03"],
["B", "2018-08-20"]
])
df.columns = ["Item", "Date"]
I want to get the first day of the week for every line of my df. I tried to do this :
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df["Day_of_Week"] = df.Date.dt.weekday
df["First_day_of_the_week"] = df.Date - timedelta(days=df.Day_of_Week)
But I got that error message :
TypeError: unsupported type for timedelta days component: Series
How can I get the first day of the week for a Series ? My expected result is that :
The dayofweek property is used to get the day of the week. The day of the week with Monday=0, Sunday=6. Note: It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the dt accessor) or DatetimeIndex.
Accessing the First Element The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value.
Pandas DataFrame first() Method The first() method returns the first n rows, based on the specified value. The index have to be dates for this method to work as expected.
A vectorised solution is possible with NumPy:
df['First_day'] = df['Date'] - df['Date'].dt.weekday * np.timedelta64(1, 'D')
print(df)
Item Date First_day
0 A 2018-08-03 2018-07-30
1 B 2018-08-20 2018-08-20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With