我的 pandas dataframe 有一个用字符串表示日期的列,它们有不同的格式,如下所示: 23MAR 其中 23 是年份,MAR 是月份,并且假定该月的结束日期, 23309 其中 23 是年,3 是月,09 是日。 我需要将这些转换成日期格式:yyyy-mm-dd (2023-03-31, 2023-03-09)
我尝试使用以下方法将这些转换为日期格式: df['Date'] = df['Date'].fillna(pd.to_datetime(df['Date'], format='%Y-%m-%d', errors='coerce') 但结果 df['Date'] 不变为 '23MAR', '23309'
非常感谢这方面的帮助
pd.offsets.MonthEnd()
和pd.dt.strftime()
尝试这个自定义函数
def parse_date(date_str):
if '-' in date_str:
return pd.to_datetime(date_str, format='%Y-%m-%d')
try:
return pd.to_datetime(date_str, format='%y%b') + pd.offsets.MonthEnd(1)
except ValueError:
return pd.to_datetime(date_str, format='%y%m%d')
df['Date'] = df['Date'].apply(parse_date).dt.strftime('%Y-%m-%d')
print(df)
Date
0 2023-03-31
1 2023-03-09
你可以试试这个:
import pandas as pd
from pandas.tseries.offsets import MonthEnd
# convert the 'date' column to datetime format with the correct format string
df['date'] = pd.to_datetime(df['date'], format='%y%b', errors='coerce').fillna(pd.to_datetime(df['date'], format='%y%m%d', errors='coerce'))
# set the day of the month to the last day of the month only for the format '23MAR'
df['date'] = df.apply(lambda row: row['date'] + MonthEnd(1) if row['date'].strftime('%d') == '01' else row['date'], axis=1)
# convert the date column to the desired format 'yyyy-mm-dd'
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
print(df)