将“熊猫”列转换为相同的日期时间格式

时间:2020-03-23 06:39:41

标签: python python-3.x pandas

我有一个文件,其中日期和时间采用以下混合格式:

Ref_ID    Date_Time
5.645217e 2020-12-02 16:23:15
5.587422e 2019-02-25 18:33:24

我要做的是将日期转换为标准格式,以便我可以进一步分析数据集。

预期结果:

Ref_ID    Date_Time
5.645217e 2020-02-12 16:23:15
5.587422e 2019-02-25 18:33:24

到目前为止,我已经尝试了一些方法,例如将Pandas转换为date_datetime并使用strptime转换日期,但是到目前为止,都没有任何作用。

# Did not work
data["Date_Time"] = pd.to_datetime(data["Date_Time"], errors="coerce")

# Also Did not work
data["Date_Time"] = data["Date_Time"].apply(lambda x: datetime.datetime.strptime(x, '%m/%d/%y'))

我也在该站点上搜索了一种解决方案,但尚未找到解决方案。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用uisng str.split提取日期和月份并使用一些布尔测试:

这可能会使所有变量有些混乱,但是我们要做的就是创建新的序列和数据框来操纵变量,这些是原始日期时间列的日期和月份

# create new dataframe with time split by space so date and time are split
s = df['Date_Time'].str.split('\s',expand=True)

# split date into its own series
m = s[0].str.split('-',expand=True).astype(int)

#use conditional logic to figure out column is the month or day.
m['possible_month'] = np.where(m[1].ge(12),m[2],m[1])
m['possible_day'] = np.where(m[1].ge(12),m[1],m[2])

#concat this back into your first split to re-create a proper datetime.
s[0] = m[0].astype(str).str.cat([m['possible_month'].astype(str),
                                 m['possible_day'].astype(str)],'-')


df['fixed_date'] = pd.to_datetime(s[0].str.cat(s[1].astype(str),' ')
                                  ,format='%Y-%m-%d %H:%M:%S')

print(df)

       Ref_ID            Date_Time          fixed_date
0  5.645217e   2020-12-02 16:23:15 2020-02-12 16:23:15
1  5.587422e   2019-02-25 18:33:24 2019-02-25 18:33:24

print(df.dtypes)

Ref_ID                object
Date_Time             object
fixed_date    datetime64[ns]
dtype: object