Note

Pandas (23) 본문

Pandas

Pandas (23)

알 수 없는 사용자 2022. 8. 14. 18:40
728x90

How to convert year-month string to dates corresponding to the 4th day of the month?

import pandas as pd

# Input
ser = pd.Series(['Jan 2010', 'Feb 2011', 'Mar 2012'])

# 1
from dateutil.parser import parse
# Parse the date
ser_ts = ser.map(lambda x: parse(x))

# Construct date string with date as 4
ser_datestr = ser_ts.dt.year.astype('str') + '-' + ser_ts.dt.month.astype('str') + '-' + '04'

# Format it.
[parse(i).strftime('%Y-%m-%d') for i in ser_datestr]

# 2
ser.map(lambda x: parse('04 ' + x))

# output
0   2010-01-04
1   2011-02-04
2   2012-03-04
dtype: datetime64[ns]

'Pandas' 카테고리의 다른 글

Pandas (25)  (0) 2022.08.16
Pandas (24)  (0) 2022.08.15
Pandas (22)  (0) 2022.08.13
Pandas (21)  (0) 2022.08.12
Pandas (20)  (0) 2022.08.11
Comments