我想将一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
我需要遍历数据框的每一行,还是有更优雅的解决方案?