设置 pd.to_datetime 的格式
Set the format for pd.to_datetime
您好,我已经提到 ,但我无法解决我的问题。我的 CSV 中有一列是字符串,下面是示例值(请注意 month
和 year
定位有时会颠倒)。我需要在 to_datetime
中设置什么格式?我尝试了以下所有方法
df = pd.read_csv("filename.csv") #Imagine there is a Month column
#[1] df["Month"] = pd.to_datetime(df["Month"])
#[2] df["Month"] = pd.to_datetime(df["Month"], format="%m/%d/%Y")
[Month]
Mar-97
Apr-97
May-97
Jun-97
Nov-00
Dec-00
1-Jan
1-Feb
1-Mar
1-Apr
我收到错误
ValueError: day is out of range for month
对于 [1],我得到
ValueError: time data 'Mar-97' does not match format '%m/%d/%Y' (match)
对于 [2]。我也尝试删除 %d
但没有成功。你能告诉我这里出了什么问题吗?
一种方法是使用 try
/ except
和 pd.Series.apply
:
s = pd.Series(['Mar-97', 'May-97', 'Nov-00', '1-Jan', '1-Mar'])
def converter(x):
try:
return pd.datetime.strptime(x, '%b-%y')
except ValueError:
year, month = x.split('-') # split by delimiter
x = year.zfill(2) + '-' + month # %y requires 0-padding
return pd.datetime.strptime(x, '%y-%b')
res = s.apply(converter)
print(res)
0 1997-03-01
1 1997-05-01
2 2000-11-01
3 2001-01-01
4 2001-03-01
dtype: datetime64[ns]
因为我们已经将converter
定义为一个函数,所以我们可以直接将其与pd.read_csv
一起使用:
df = pd.read_csv('file.csv', parse_dates=['dt_col_name'], date_parser=converter)
Python's strftime directives 是构建 datetime
格式字符串的有用参考。
不是最优雅的,但您可以尝试修复和排序年份和月份部分。以下代码有效:
重新创建您的数据:
df = pd.DataFrame({"date_str": ['Mar-97', 'Apr-97', 'May-97',
'Jun-97', 'Nov-00', 'Dec-00',
'1-Jan', '1-Feb', '1-Mar', '1-Apr']})
拆分部分:
df = pd.concat([df, df['date_str'].str.split("-", expand=True)], axis=1)
整理月份和年份:
df.loc[df[0].str.len() == 3, 'month'] = df.loc[df[0].str.len() == 3, 0]
df.loc[df[1].str.len() == 3, 'month'] = df.loc[df[1].str.len() == 3, 1]
df.loc[df[0].str.len() != 3, 'year'] = df.loc[df[0].str.len() != 3, 0]
df.loc[df[1].str.len() != 3, 'year'] = df.loc[df[1].str.len() != 3, 1]
更正只有一个数字的年份:
df.loc[df['year'].str.len() == 1, 'year'] = '0' + df.loc[df['year'].str.len() == 1, 'year']
生成正确的日期列:
df['date'] = (df['month'] + '-' + df['year']).apply(lambda x: pd.to_datetime(x, format="%b-%y"))
输出:
print(df['date'])
0 1997-03-01
1 1997-04-01
2 1997-05-01
3 1997-06-01
4 2000-11-01
5 2000-12-01
6 2001-01-01
7 2001-02-01
8 2001-03-01
9 2001-04-01
Name: date, dtype: datetime64[ns]
您好,我已经提到 month
和 year
定位有时会颠倒)。我需要在 to_datetime
中设置什么格式?我尝试了以下所有方法
df = pd.read_csv("filename.csv") #Imagine there is a Month column
#[1] df["Month"] = pd.to_datetime(df["Month"])
#[2] df["Month"] = pd.to_datetime(df["Month"], format="%m/%d/%Y")
[Month]
Mar-97
Apr-97
May-97
Jun-97
Nov-00
Dec-00
1-Jan
1-Feb
1-Mar
1-Apr
我收到错误
ValueError: day is out of range for month
对于 [1],我得到
ValueError: time data 'Mar-97' does not match format '%m/%d/%Y' (match)
对于 [2]。我也尝试删除 %d
但没有成功。你能告诉我这里出了什么问题吗?
一种方法是使用 try
/ except
和 pd.Series.apply
:
s = pd.Series(['Mar-97', 'May-97', 'Nov-00', '1-Jan', '1-Mar'])
def converter(x):
try:
return pd.datetime.strptime(x, '%b-%y')
except ValueError:
year, month = x.split('-') # split by delimiter
x = year.zfill(2) + '-' + month # %y requires 0-padding
return pd.datetime.strptime(x, '%y-%b')
res = s.apply(converter)
print(res)
0 1997-03-01
1 1997-05-01
2 2000-11-01
3 2001-01-01
4 2001-03-01
dtype: datetime64[ns]
因为我们已经将converter
定义为一个函数,所以我们可以直接将其与pd.read_csv
一起使用:
df = pd.read_csv('file.csv', parse_dates=['dt_col_name'], date_parser=converter)
Python's strftime directives 是构建 datetime
格式字符串的有用参考。
不是最优雅的,但您可以尝试修复和排序年份和月份部分。以下代码有效:
重新创建您的数据:
df = pd.DataFrame({"date_str": ['Mar-97', 'Apr-97', 'May-97',
'Jun-97', 'Nov-00', 'Dec-00',
'1-Jan', '1-Feb', '1-Mar', '1-Apr']})
拆分部分:
df = pd.concat([df, df['date_str'].str.split("-", expand=True)], axis=1)
整理月份和年份:
df.loc[df[0].str.len() == 3, 'month'] = df.loc[df[0].str.len() == 3, 0]
df.loc[df[1].str.len() == 3, 'month'] = df.loc[df[1].str.len() == 3, 1]
df.loc[df[0].str.len() != 3, 'year'] = df.loc[df[0].str.len() != 3, 0]
df.loc[df[1].str.len() != 3, 'year'] = df.loc[df[1].str.len() != 3, 1]
更正只有一个数字的年份:
df.loc[df['year'].str.len() == 1, 'year'] = '0' + df.loc[df['year'].str.len() == 1, 'year']
生成正确的日期列:
df['date'] = (df['month'] + '-' + df['year']).apply(lambda x: pd.to_datetime(x, format="%b-%y"))
输出:
print(df['date'])
0 1997-03-01
1 1997-04-01
2 1997-05-01
3 1997-06-01
4 2000-11-01
5 2000-12-01
6 2001-01-01
7 2001-02-01
8 2001-03-01
9 2001-04-01
Name: date, dtype: datetime64[ns]