我正在将日期时间格式的数据导出到 csv。当我将它导入回来时,我需要能够在没有任何列名或列号引用的情况下将数据作为日期读取。
看起来 Pandas read_csv 具有将日期自动解析为日期时间格式的选项,但它似乎在这里不起作用。
# Create date data
df_list = [['2014-01-01','2014-02-01'],['2015-01-01','2015-02-01']]
df = pd.DataFrame(df_list,columns=['date1','date2'])
# Convert to datetime format
df['date1'] = pd.to_datetime(df['date1'])
# Export to csv
df.to_csv('_csv_file.csv',index=False)
# Read in the data and parse dates
in_df = pd.read_csv('_csv_file.csv',parse_dates=True,infer_datetime_format=True)
# Dates are not of correct type
print df.dtypes
print
print in_df.dtypes
Out [1]:
date1 datetime64[ns]
date2 object
dtype: object
date1 object
date2 object
dtype: object
有没有办法在导入时自动解析日期列而无需明确识别列名或位置?
最佳答案
我觉得你可以换 True
至 ['date1']
在参数 parse_dates
中的 read_csv
, 因为 True
表示解析 index
和 ['date1']
解析列date1
:
# Read in the data and parse dates
in_df = pd.read_csv('_csv_file.csv', parse_dates=['date1'], infer_datetime_format=True )
#second solution
#instead column name - number of column
#in_df = pd.read_csv('_csv_file.csv',parse_dates=[0], infer_datetime_format=True )
# Dates are not of correct type
print df.dtypes
print
print in_df.dtypes
date1 datetime64[ns]
date2 object
dtype: object
date1 datetime64[ns]
date2 object
dtype: object
Docs :parse_dates : boolean, list of ints or names, list of lists, or dict, default False
If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’ A fast-path exists for iso8601-formatted dates.
infer_datetime_format : boolean, default False
If True and parse_dates is enabled for a column, attempt to infer the datetime format to speed up the processing
如果您设置列
date1
,它会起作用作为索引:# Read in the data and parse dates
in_df = pd.read_csv('_csv_file.csv', parse_dates=True, infer_datetime_format=True,
index_col='date1' )
# Dates are not of correct type
print
print in_df.dtypes
print in_df.index
date2 object
dtype: object
DatetimeIndex(['2014-01-01', '2015-01-01'], dtype='datetime64[ns]', name=u'date1', freq=None)
编辑:如果要将所有列解析为
datetime
,您可以通过列数指定所有列到参数 parse_dates
:in_df = pd.read_csv('_csv_file.csv', parse_dates=[0, 1, 2, 3])
但可能存在错误 - 一些 integers
可以解析为 datetimes
例如。:print df
print df.dtypes
date1 date2 int1 int2
0 2014-01-01 2014-02-01 2000 20111230
1 2015-01-01 2015-02-01 2014 20151230
date1 datetime64[ns]
date2 object
int1 int64
int2 int64
dtype: object
print
print in_df
print in_df.dtypes
date1 date2 int1 int2
0 2014-01-01 2014-02-01 2000-01-01 2011-12-30
1 2015-01-01 2015-02-01 2014-01-01 2015-12-30
date1 datetime64[ns]
date2 datetime64[ns]
int1 datetime64[ns]
int2 datetime64[ns]
dtype: object
关于date - parse_dates 不适用于默认日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34604509/