下面是简单的例子使用验证:
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
data = DataFrame(np.arange(15).reshape(3,5),index=['one','two','three'],columns=['a','b','c','d','e'])
data
Out[7]:
a b c d e
one 0 1 2 3 4
two 5 6 7 8 9
three 10 11 12 13 14
#对列的操作方法有如下几种
data.icol(0) #选取第一列
E:\Anaconda2\lib\site-packages\spyder\utils\ipython\start_kernel.py:1: FutureWarning: icol(i) is deprecated. Please use .iloc[:,i]
# -*- coding: utf-8 -*-
Out[35]:
one 0
two 5
three 10
Name: a, dtype: int32
data['a']
Out[8]:
one 0
two 5
three 10
Name: a, dtype: int32
data.a
Out[9]:
one 0
two 5
three 10
Name: a, dtype: int32
data[['a']]
Out[10]:
a
one 0
two 5
three 10
data.ix[:,[0,1,2]] #不知道列名只知道列的位置时
Out[13]:
a b c
one 0 1 2
two 5 6 7
three 10 11 12
data.ix[1,[0]] #选择第2行第1列的值
Out[14]:
a 5
Name: two, dtype: int32
data.ix[[1,2],[0]] #选择第2,3行第1列的值
Out[15]:
a
two 5
three 10
data.ix[1:3,[0,2]] #选择第2-4行第1、3列的值
Out[17]:
a c
two 5 7
three 10 12
data.ix[1:2,2:4] #选择第2-3行,3-5(不包括5)列的值
Out[29]:
c d
two 7 8
data.ix[data.a>5,3]
Out[30]:
three 13
Name: d, dtype: int32
data.ix[data.b>6,3:4] #选择'b'列中大于6所在的行中的第4列,有点拗口
Out[31]:
d
three 13
data.ix[data.a>5,2:4] #选择'a'列中大于5所在的行中的第3-5(不包括5)列
Out[32]:
c d
three 12 13
data.ix[data.a>5,[2,2,2]] #选择'a'列中大于5所在的行中的第2列并重复3次
Out[33]:
c c c
three 12 12 12
#还可以行数或列数跟行名列名混着用
data.ix[1:3,['a','e']]
Out[24]:
a e
two 5 9
three 10 14
data.ix['one':'two',[2,1]]
Out[25]:
c b
one 2 1
two 7 6
data.ix[['one','three'],[2,2]]
Out[26]:
c c
one 2 2
three 12 12
data.ix['one':'three',['a','c']]
Out[27]:
a c
one 0 2
two 5 7
three 10 12
data.ix[['one','one'],['a','e','d','d','d']]
Out[28]:
a e d d d
one 0 4 3 3 3
one 0 4 3 3 3
#对行的操作有如下几种:
data[1:2] #(不知道列索引时)选择第2行,不能用data[1],可以用data.ix[1]
Out[18]:
a b c d e
two 5 6 7 8 9
data.irow(1) #选取第二行
Out[36]:
a 5
b 6
c 7
d 8
e 9
Name: two, dtype: int32
data.ix[1] #选择第2行
Out[20]:
a 5
b 6
c 7
d 8
e 9
Name: two, dtype: int32
data['one':'two'] #当用已知的行索引时为前闭后闭区间,这点与切片稍有不同。
Out[22]:
a b c d e
one 0 1 2 3 4
two 5 6 7 8 9
data.ix[1:3] #选择第2到4行,不包括第4行,即前闭后开区间。
Out[23]:
a b c d e
two 5 6 7 8 9
three 10 11 12 13 14
data.ix[-1:] #取DataFrame中最后一行,返回的是DataFrame类型,**注意**这种取法是有使用条件的,只有当行索引不是数字索引时才可以使用,否则可以选用`data[-1:]`--返回DataFrame类型或`data.irow(-1)`--返回Series类型
Out[11]:
a b c d e
three 10 11 12 13 14
data[-1:] #跟上面一样,取DataFrame中最后一行,返回的是DataFrame类型
Out[12]:
a b c d e
three 10 11 12 13 14
data.ix[-1] #取DataFrame中最后一行,返回的是Series类型,这个一样,行索引不能是数字时才可以使用
Out[13]:
a 10
b 11
c 12
d 13
e 14
Name: three, dtype: int32
data.tail(1) #返回DataFrame中的最后一行
data.head(1) #返回DataFrame中的第一行
网友评论