假设目前已经引入了 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

最新文章

  1. DECLARE_GLOBAL_DATA_PTR宏定义问题
  2. 深入分析:Android中app之间的交互(一,使用Action)
  3. SQL存储过程和触发器
  4. php测试代码工具类
  5. HDU 5351 MZL&#39;s Border (规律,大数)
  6. 利用MVC的过滤器实现url的参数加密和解密
  7. 防止自己的网站被别人frame引用造成钓鱼
  8. js多个物体运动的问题1
  9. Bridge 设计模式
  10. Elasticsearch布尔查询——bool
  11. angular2 学习笔记 ( translate, i18n 翻译 )
  12. WIN7电脑文件莫名其妙被删除后的恢复
  13. 了解vue里的Runtime Only和Runtime+Compiler
  14. 【ASP.NET Core快速入门】(八)Middleware管道介绍、自己动手构建RequestDelegate管道
  15. jsp 异步处理
  16. layui 将后台传过来的值等价替换
  17. 【C/C++】C/C++中的数组是怎么实现的?
  18. ZJUT 地下迷宫 (高斯求期望)
  19. 【Linux】top命令
  20. 餐E评echarts

热门文章

  1. ADT Android Development Tools
  2. 【转】WCF服务的创建和发布到IIS
  3. 【转】C# URL短地址压缩算法及短网址原理解析
  4. 【Java面试题】50 垃圾回收器的基本原理是什么?垃圾回收器可以马上回收内存吗?有什么办法主动通知虚拟机进行垃圾回收?
  5. 【Java NIO的深入研究2】RandomAccessFile的使用
  6. 【Java面试题】16 静态代码块,main方法,构造代码块,构造方法
  7. js定义对象
  8. 解决导入protobuf源代码Unity报错的问题
  9. MongoDB创建表步骤,Mongo常用的数据库操作命令,查询,添加,更新,删除_MongoDB 性能监测
  10. swift--动画效果