书里介绍索引方法以罗列为主,看完容易记住难,并没有把几种索引方法总结归纳出来。所以本篇学习笔记,我争取把几种索引方法总结出来,便于记忆。
目录
- 一、Series对象索引
- 1、['索引名'] or ['索引名1' : '索引名2'] or [['索引名1', ..., '索引名n']]
 - 2、[整数] or [整数1:整数2] or [[整数1,..., 整数n]]
 - 3、[布尔表达式]
 
 - 二、DataFrame对象索引
- 1、['列名1'] or ['列名1',..., '列名n']
 - 2、[整数1:整数2]
 - 3、[布尔表达式]
 - 4、ix方法:DataFrame.ix['列名', ['索引名1',..., '索引名n']]
 
 
一、Series对象索引
1、['索引名'] or ['索引名1' : '索引名2'] or [['索引名1', ..., '索引名n']]
注:['索引名1' : '索引名2']取出的数组是左右都包含的。
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
obj = Series(np.arange(4.), index = ['a', 'b', 'c', 'd'])
obj['a']
输出:0.0
obj['a':'c']
输出:
a    0.0
b    1.0
c    2.0
dtype: float64
obj[['a', 'b', 'c']]
输出:
a    0.0
b    1.0
c    2.0
dtype: float64
2、[整数] or [整数1:整数2] or [[整数1,..., 整数n]]
[整数1:整数2]取出的数组是包含整数1不包括整数2的。
obj[1]
输出:1.0
obj[1:3]
输出:
b    1.0
c    2.0
dtype: float64
obj[[0, 2]]
输出:
a    0.0
c    2.0
dtype: float64
3、[布尔表达式]
obj[obj<2]
输出:
a    0.0
b    1.0
dtype: float64
二、DataFrame对象索引
DataFrame对象与Series对象索引的区别在于,在index(索引名)基础上还有columns(列名)。
1、['列名1'] or [['列名1',..., '列名n']]
data = DataFrame(np.arange(16).reshape((4, 4)), index = ['Ohio', 'Colorado', 'Utah', 'New York'], columns = ['one', 'two', 'three', 'four'])
data
输出:
    one two three   four
Ohio    0   1   2   3
Colorado    4   5   6   7
Utah    8   9   10  11
New York    12  13  14  15
data['one']
输出:
Ohio         0
Colorado     4
Utah         8
New York    12
Name: one, dtype: int64
data[['one', 'three']]
输出:
    one three
Ohio    0   2
Colorado    4   6
Utah    8   10
New York    12  14
2、[整数1:整数2]
这个方法是对行名进行索引。
data[0:2]
输出:
    one two three   four
Ohio    0   1   2   3
Colorado    4   5   6   7
data[1:]
输出:
    one two three   four
Colorado    4   5   6   7
Utah    8   9   10  11
New York    12  13  14  15
3、[布尔表达式]
data[data['three']>5]
输出:
    one two three   four
Colorado    4   5   6   7
Utah    8   9   10  11
New York    12  13  14  15
4、ix方法:DataFrame.ix['列名', ['索引名1',..., '索引名n']]
ix方法可以对index及columns都进行索引。
data.ix['Colorado', ['two', 'three']]
输出:
two      5
three    6
Name: Colorado, dtype: int64
data.ix[['Colorado', 'Utah'], [1, 0, 3]]
输出:
    two one four
Colorado    5   4   7
Utah    9   8   11
好了,Series和DataFrame的索引方法就总结到这里,自以为比书里的清晰一些吼吼。