1. 简介
Pandas以类似字典的方式来获取某一列的值,比如df[‘A’],这会得到df的A列。
操作行时通常使用两种方法:一种是iloc方法,另一种方法是loc方法。
loc是指location的意思,iloc中的i是指integer。
loc:根据index来索引。
iloc:根据行号来索引,行号从0开始,逐次加1。
2. 示例
In [1]: df = DataFrame(randn(5,2),index=range(0,10,2),columns=list('AB'))
In [2]: df
Out[2]:
A B
0 1.068932 -0.794307
2 -0.470056 1.192211
4 -0.284561 0.756029
6 1.037563 -0.267820
8 -0.538478 -0.800654
In [5]: df.iloc[[2]]
Out[5]:
A B
4 -0.284561 0.756029
In [6]: df.loc[[2]]
Out[6]:
A B
2 -0.470056 1.192211
3. 补充1
iloc的一种更典型的用法是iloc[ : , : ]。
前面的冒号是取行数,后面的冒号是取列数。而且,都遵循左闭右开原则。
例如下面的DataFrame结构:
import pandas
df=pandas,read_csv('a.csv')
print(df.iloc[1,2])
#output: 95