DataFrame.iloc
纯基于整数位置的索引。
.iloc[]主要是整数位置(来自0于 length-1所述轴线的),但也可以用布尔阵列使用。
允许的输入为:
- 整数,例如5。
- 整数列表或数组,例如。[4, 3, 0]
- 具有整数的切片对象,例如1:7。
- 布尔数组。
- 一个callable具有一个参数的函数(调用Series或DataFrame),并且返回用于索引的有效输出(上述之一)。当没有对调用对象的引用,但希望基于某个值进行选择时,这在方法链中很有用。
.ilocIndexError如果所请求的索引器超出边界,则将提高,但切片索引器除外,该索引器允许进行越界索引(这与python / numpy slice语义一致)。
import pandas as pd
mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
{'a': 100, 'b': 200, 'c': 300, 'd': 400},
{'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
mydict
[{'a': 1, 'b': 2, 'c': 3, 'd': 4},
{'a': 100, 'b': 200, 'c': 300, 'd': 400},
{'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000}]
df = pd.DataFrame(mydict)
df
a b c d
0 1 2 3 4
1 100 200 300 400
2 1000 2000 3000 4000
df.iloc[0]
a 1
b 2
c 3
d 4
Name: 0, dtype: int64
df.iloc[0].shape
(4,)
type(df.iloc[0].shape)
tuple
df.iloc[[0]]
a b c d
0 1 2 3 4
type(df.iloc[[0]])
pandas.core.frame.DataFrame
df.iloc[[0,2]]
a b c d
0 1 2 3 4
2 1000 2000 3000 4000
df.iloc[0:2,0:3]
a b c
0 1 2 3
1 100 200 300
df.iloc[[True, False, True]]#不常用
a b c d
0 1 2 3 4
2 1000 2000 3000 4000
df.iloc[lambda x: x.index % 2 == 0]#函数生成索引列表,x即df
a b c d
0 1 2 3 4
2 1000 2000 3000 4000