Python 熊猫:将日期转换为文本,例如 Aug 2018 --> 08-2018 或 01-08-2018



>转换日期,例如 2018 年 8 月 --> 01-08-2018 ??

这是我的示例输入

id      year_pass
1       Aug 2018 - Nov 2018
2       Jul 2017 - Oct 2017

输出应为:

id      year_pass
1       01-08-2018
2       01-07-2017 

id      year_start    year_end
1       01-08-2018    01-11-2018
2       01-07-2018    01-10-2018

这是一个解决方案。

import pandas as pd
import numpy as np
from datetime import datetime
# creating the sample dataframe
df = pd.DataFrame([[0.57, 'Aug 2018 - Nov 2018'], 
                   [0.11, 'Jul 2017 - Oct 2017']], 
                   columns=['id', 'year_pass'])
# splitting the date column on the '-'
year_start, year_end = df['year_pass'].str.split('-')
df.drop('year_pass', axis=1, inplace=True)
# assigning the split values to columns
df['year_start'] = year_start
df['year_end'] = year_end
# converting to datetime objects
df['year_start'] = pd.to_datetime(df['year_start'])
df['year_end'] = pd.to_datetime(df['year_end'])
您可以

先像这样拆分year_pass列:

new_df = df.year_pass.str.split(' - ')
new_df1 = new_df.apply(pd.Series)
new_df2 = pd.to_datetime(new_df1[0])

然后,您可以将生成的数据帧合并到实际数据帧。把它放在一行代码中:

new_df = pd.to_datetime(df.year_pass.str.split(' - ').apply(pd.Series)[0])

日期格式为 YYYY-MM-DD,而不是 DD-MM-YYYY

最新更新