Pandas 数据选取之loc iloc ix
2017-08-26 本文已影响0人
减个肥怎么就那么难
基于想同时学习金融和pandas的初衷,代码实例会使用到tushare
话题部分源于Data analysis in Python with pandas, 权当是学习笔记吧
import pandas as pd
import tushare as ts
loc
用标签(index 范围, column 范围)来选取数据
price = ts.get_hist_data('000063')
price.head(10)

当我只需要取 8月15日到8月21日之间的数据
price.loc['2017-08-21':'2017-08-15', :]

当我只需要取 8月15日到8月21日之间的数据, 并且只要开盘、最高、收盘、最低价
price.loc['2017-08-21':'2017-08-15', 'open':'low']

iloc
用位置(index 范围, column 范围)来选取数据, i 代表的是 integer,整数,位置
当我只需要取 8月15日(第八行)到8月21日(第四行)之间的数据, 并且只要开盘、最高、收盘、最低价(前4列)
price.iloc[4:8, 0:3]

好像不太对?因为4:8 0:3 并不包含第8行以及第4列,iloc的参数和python列表切片以及range方法是一样的,取值的时候不包含右边的参数!
price.iloc[4:9, 0:4]

如果 dataFrame的index本身就是integer呢?
price.reset_index(inplace=True)
price.head()

price.loc[4:8, 'date':'low']

[4:8] 第八行显然是包括进去的,这是loc 和 iloc遇到整型标签的时候需要注意的地方。
ix
是loc 和 iloc的混合物,当标签为整型的时候,使用loc方法,否则使用iloc
price.ix[4:8, 0:4]

话说Juypter的md文件不能直接贴到简书里啊,心累