将pandas dataframe列转换为np.datetime64

时间:2016-11-11 04:47:19

标签: python pandas numpy datetime64

我想将一个np.datetime64列添加到已从包含年,月,日,小时和分钟列的.csv文件中读取的pandas数据框中,并将其用作索引。我将单独的列组合在一起构成了一列日期时间字符串。

import numpy as np
import pandas as pd
filename = 'test.csv'
df = pd.read_csv(filename, header=0, usecols = [2,3,4,5,6], names = ['y','m','d','h','min'],dtype = {'y':'str','m':'str','d':'str','h':'str','min':'str'})  #read csv file into df
df['datetimetext'] = (df['y']+'-'+df['m']+'-'+df['d']+' '+df['h']+':'+df['min']+':00')

所以数据框看起来像这样:

           y   m   d   h min    datetimetext  
0       1993  09  06  00  30    1993-09-06 00:30:00
1       1993  09  06  01  00    1993-09-06 01:00:00
2       1993  09  06  01  30    1993-09-06 01:30:00
3       1993  09  06  02  00    1993-09-06 02:00:00
4       1993  09  06  02  30    1993-09-06 02:30:00
......

现在我想添加一个日期时间格式为np.datetime64

的列

我想写

df['datetime'] = np.datetime64(df['datetimetext'])

但是会产生错误

ValueError: Could not convert object to NumPy datetime

我是否需要遍历数据框的每一行,还是有更优雅的解决方案?

1 个答案:

答案 0 :(得分:5)

最简单的方法是

df['datetime'] = pd.to_datetime(df['datetimetext'])

LINK TO DOCS

但是,如果列的名称相应,则可以直接从命名列进行转换。我使用rename

重命名了您的列
m = dict(y='year', m='month', d='day', h='h', min='m')
# rename columns and get rid of datetimetext
df = df[['y', 'm', 'd', 'h', 'min']].rename(columns=m)
df

enter image description here

我接下来执行转换并一次性分配给索引

df.index = pd.to_datetime(df)
df

enter image description here