简体   繁体   中英

How to change date type from 'year_week' to 'day_month_year' format in pandas dataframe?

Image of dataset

I have a dataset but date is given in year_week format. I want to change it to normal 'day_month_year' format and set it as an index.

df["Date"] = df["year_week"].astype(str)
df["Date"]=pd.to_datetime(df["Date"])
df['Date'] = df['Date'].dt.strptime("{}-{}-1".format(int(df['Date'].split('-')[0]),  int(df['Date'].split('-')[1])), '%Y-%W-%w')
df.set_index('Date',inplace=True)
df.drop('year_week',inplace=True,axis=1)
df.head()

but it gives bad month numver 13; must be 1-12 error your text

append the weekday as a string (see also: strftime/strptime formatting codes ), parse to datetime, then format to string in desired format:

import pandas as pd

df = pd.DataFrame({"year_week": ["2020-01", "2020-02"]})

# parse to datetime, then format to string
df["day_month_year"] = pd.to_datetime(df["year_week"]+"-0", format="%Y-%W-%w").dt.strftime("%d-%m-%Y")

print(df)
  year_week day_month_year
0   2020-01     12-01-2020
1   2020-02     19-01-2020

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM