假设目前已经引入了 pandas,同时也拥有 pandas 的 DataFrame 类型数据。

import pandas as pd

数据集如下

df.head(3)
        date    open    close    high    low        volume        code
0 2006-12-18 3.905 3.886 3.943 3.867 171180.67 600001
1 2006-12-19 3.886 3.924 3.981 3.867 276799.39 600001
2 2006-12-20 3.934 3.934 3.962 3.809 265653.85 600001

查看每一列的类型

df.info()

从结果的第四排可以看见 date 这一列类型是"object",即字符类型。

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 640 entries, 0 to 639
Data columns (total 7 columns):
date 640 non-null object
open 640 non-null float64
close 640 non-null float64
high 640 non-null float64
low 640 non-null float64
volume 640 non-null float64
code 640 non-null object
dtypes: float64(5), object(2)
memory usage: 35.1+ KB

现在的目标是:

  • 把 date 这一列用作索引
  • 把 date 用作索引时,类型需要是 DatetimeIndex。

方法1: .to_datetime 和 .set_index

首先,利用 pandas 的to_datetime 方法,把 "date" 列的字符类型数据解析成 datetime 对象。

然后,把 "date" 列用作索引。

df['date'] = pd.to_datetime(df['date'])
df.set_index("date", inplace=True)

结果:

df.head(3)
            open    close    high    low        volume        code
date
2006-12-18 3.905 3.886 3.943 3.867 171180.67 600001
2006-12-19 3.886 3.924 3.981 3.867 276799.39 600001
2006-12-20 3.934 3.934 3.962 3.809 265653.85 600001

查看索引是否成为 DatetimeIndex 类型,可以看见确实已经成功转化类型。

df.axes
[DatetimeIndex(['2006-12-18', '2006-12-19', '2006-12-20', '2006-12-21',
'2006-12-22', '2006-12-25', '2006-12-26', '2006-12-27',
'2006-12-28', '2006-12-29',
...
'2009-12-02', '2009-12-03', '2009-12-04', '2009-12-07',
'2009-12-08', '2009-12-09', '2009-12-10', '2009-12-11',
'2009-12-14', '2009-12-15'],
dtype='datetime64[ns]', name='date', length=640, freq=None),
Index(['open', 'close', 'high', 'low', 'volume', 'code'], dtype='object')]

方法2: .DatetimeIndex

首先是原始数据。

df2.head(3)
        date    open    close    high    low        volume        code
0 2003-08-01 4.997 4.949 5.016 4.949 20709.15 600002
1 2003-08-04 4.949 5.045 5.054 4.949 23923.35 600002
2 2003-08-05 5.054 5.093 5.131 5.006 35224.00 600002

先把 "date" 列用作索引,然后使用 DatetimeIndex 将字符类型转化成 DateIndex

df2.set_index("date", inplace=True)

这个时候索引还是 object 类型,就是字符串类型。

df2.axes
[Index(['2003-08-01', '2003-08-04', '2003-08-05', '2003-08-06', '2003-08-07',
'2003-08-08', '2003-08-11', '2003-08-12', '2003-08-13', '2003-08-14',
...
'2006-03-24', '2006-03-27', '2006-03-28', '2006-03-29', '2006-03-30',
'2006-03-31', '2006-04-03', '2006-04-04', '2006-04-05', '2006-04-06'],
dtype='object', name='date', length=640),
Index(['open', 'close', 'high', 'low', 'volume', 'code'], dtype='object')]

将其转化成 DateIndex 类型。

df2.index = pd.DatetimeIndex(df.index)

再次查看结果

df2.axes

转化成功

[DatetimeIndex(['2006-12-18', '2006-12-19', '2006-12-20', '2006-12-21',
'2006-12-22', '2006-12-25', '2006-12-26', '2006-12-27',
'2006-12-28', '2006-12-29',
...
'2009-12-02', '2009-12-03', '2009-12-04', '2009-12-07',
'2009-12-08', '2009-12-09', '2009-12-10', '2009-12-11',
'2009-12-14', '2009-12-15'],
dtype='datetime64[ns]', name='date', length=640, freq=None),
Index(['open', 'close', 'high', 'low', 'volume', 'code'], dtype='object')]

结论:.to_datetime仅转换格式,.DatetimeIndex还能设置为索引

两者在转化格式的功能上效果一样,都可以把字符串对象转换成 datetime 对象。

pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
比如

df2.index = pd.DatetimeIndex(df2["date"])

得到一个以 date 作为索引的结果。

.DatetimeIndex 的问题是原来的 date 列数据仍然存在,形成了重复。

                        date           open    close    high              low            volume    code
date
2003-08-01 2003-08-01 4.997 4.949 5.016 4.949 20709.15 600002
2003-08-04 2003-08-04 4.949 5.045 5.054 4.949 23923.35 600002
2003-08-05 2003-08-05 5.054 5.093 5.131 5.006 35224.00 600002

最终还需要把 date 这一列删掉。

del df2["date"]

才能得到正常数据

               open    close    high    low    volume    code
date
2003-08-01 4.997 4.949 5.016 4.949 20709.15 600002
2003-08-04 4.949 5.045 5.054 4.949 23923.35 600002
2003-08-05 5.054 5.093 5.131 5.006 35224.00 600002

 

原文链接:http://www.jianshu.com/p/4ece5843d383

pandas将字段中的字符类型转化为时间类型,并设置为索引的更多相关文章

  1. 【SQLite】使用replace替换字段中的字符

    使用replace替换字段中的字符 如:替换production表中的specification字段中的两个空格为一个空格: update production set specification = ...

  2. SQL 判断字段中指定字符出现的次数

    原文地址:SQL 判断字段中指定字符出现的次数 原理:将指定字符转换为空,原长度减去转换后的长度就是指定字符的次数. 在做数据处理时遇到一个SQL操作的问题就是有一列关键词字段,字段中包含各种乱七八糟 ...

  3. mysql面试题:字段中@之前字符相同且大于等于2条的所有记录

    公司发了一张面试题给我,题目如下: 在test数据库中有个flow_user表,找出email字段中@之前字符相同且大于等于2条的所有记录 答案: select substring_index(`em ...

  4. sql替换数据库字段中的字符

    UPDATE `table_name` SET `field_name` = replace (`field_name`,'from_str','to_str') WHERE ……说明:table_n ...

  5. mysql命令语句来去除掉字段中空格字符的方法

    mysql有什么办法批量去掉某个字段字符中的空格?不仅是字符串前后的空格,还包含字符串中间的空格,答案是 replace,使用mysql自带的 replace 函数,另外还有个 trim 函数.   ...

  6. js中如何将字符串转化为时间,并计算时间差

    在前台页面开发时通常会用到计算两个时间的时间差,先在此附上实现方法 //结束时间 end_str = ("2014-01-01 10:15:00").replace(/-/g,&q ...

  7. pandas 数据表中的字符与日期数据的处理

    前面我们有学习过有关字符串的处理和正在表达式,但那都是基于单个字符串或字符串列表的操作.下面将学习如何基于数据框操作字符型变量. 同时介绍一下如何从日期型变量中取出年份,月份,星期几等,如何计算两个日 ...

  8. 为什么我们要使用int类型来保存时间类型的数据。

    1.如果数据保存的是timestamp类型那么,如果某个服务器系统时区配置错误,那么悲剧的是通过该服务器写入的时间都是有偏差的.  如果使用int类型保存unix时间戳的话,那么就是在前端展示的时候转 ...

  9. bootstropt-table 大量字段整体表单上传之时间处理

    js 中用$('#addUserForm').serialize(),//获取表单中所有数据 传送到前台 (controller) $.ajax({ type : "POST", ...

随机推荐

  1. Qt信号槽的一些事

    注:此文是站在Qt5的角度说的,对于Qt4部分是不适用的. 1.先说Qt信号槽的几种连接方式和执行方式. 1)Qt信号槽给出了五种连接方式: Qt::AutoConnection 0 自动连接:默认的 ...

  2. Asynchronous Methods for Deep Reinforcement Learning(A3C)

    Mnih, Volodymyr, et al. "Asynchronous methods for deep reinforcement learning." Internatio ...

  3. Spring4 Web开发新特性

    基于Servlet3开发. 针对RESTful开发,提供了@RestController,加在Controller上面,免除了每个@RequestMapping method上面的@ResponseB ...

  4. 有一个TIME的类要求输出分和秒的值

    #include <iostream> /* run this program using the console pauser or add your own getch, system ...

  5. Wellner 自适应阈值二值化算法

    参考文档: Adaptive Thresholding for the DigitalDesk.pdf       Adaptive Thresholding Using the Integral I ...

  6. (转)MPEG4码流简单分析

    把MPEG4码流的分析和它的I,P,B Frame的判定方法在这里简要记录一下吧,供日后的翻看和大家的参考.   测试解码器测试了很久,由于需要将H264和MPEG4的码流进行分析和判断,并逐帧输入解 ...

  7. Javascript农历与公历相互转换

    /**用法 * Lunar.toSolar(2016, 6, 3); 农历转化公历 * Lunar.toLunar(2016, 7, 6); 公历转化农历 */ var Lunar = { MIN_Y ...

  8. R语言中的标准输入,输出, 错误流

    在R中,stdin() 对应标准输入流 , stdout() 对应标准输出流,stderr() 对应标准错误流 1) 从标准输入流中读取数据 在R的交互式环境中, R >a <- read ...

  9. vnc远程控制软件怎么用

    CC是一款不错的局域网控制软件,它的轻便让人无法相信,下载过该软件的人都知道,该软件只有大小 工具/原料   我这里使用的是vnc-E4_2_9X32中文版 被控制端的安装   1 我们先来被控制电脑 ...

  10. Session超时问题(AOP 过滤器)

    public class TimeoutAttribute : ActionFilterAttribute { public override void OnActionExecuting(Actio ...