date - parse_dates 不适用于默认日期时间格式

标签 date csv pandas

我正在将日期时间格式的数据导出到 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/

相关文章:

python - 如何使用 xrange 的结果打印列表 (CSV) 中的行?

java - 我的 Java 程序没有生成 CSV 输出

php - 在 MySQL 中查找给定的日期范围是否在另一个日期范围内

javascript - 使用JS和Jquery将 'Month and Year'字符串转换成Date对象

mysql - 操作 VARCHAR 字符串并更新列(伪日期)

java - 为什么不在 Jdbc 中使用 java.util.Date?

MySQL 从 CSV 数据加载空值错误代码 1582

pandas - 如何将字符串值拆分/扩展为多个 pandas DataFrame 行?

python - 为什么 str.cat 比 python 中的 lambda 表达式快得多?

python-3.x - 如何在pandas中将列名传递给参数