Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first day of the week for a Pandas series

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 :

  • "A", "2018-08-03", "2018-07-30"
  • "B", "2018-08-20", "2018-08-20"
like image 892
Charles R Avatar asked Jul 06 '18 10:07

Charles R


People also ask

How do you get the day of the week in Pandas?

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.

How do you get the first element in a Pandas series?

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.

What does First () do in Pandas?

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.


1 Answers

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
like image 60
jpp Avatar answered Oct 21 '22 01:10

jpp