Pandas-按索引从df中读取指定一个或者多个元素
df.iloc
Purely integer-location based indexing for selection by position. 按索引读取指定一个或者多个元素
Allowed inputs are:
An integer, e.g. 5.
A list or array of integers, e.g. [4, 3, 0].
A slice object with ints, e.g. 1:7.
A boolean array.
A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.
A tuple of row and column indexes. The tuple elements consist of one of the above inputs, e.g. (0, 1).
允许的输入包括:
- 一个整数,例如 5。
- 一个整数列表或数组,例如 [4, 3, 0]。
- 带有整数的切片对象,例如 1:7。
- 一个布尔数组。
- 一个带有单个参数(调用的 Series 或 DataFrame)的可调用函数,并且该函数返回可用于索引的有效输出(上述之一)。这在方法链中很有用,当你没有调用对象的引用,但想要根据某些值进行选择时。
- 行和列索引的元组。元组元素由上述输入之一组成,例如 (0, 1)。
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
Indexing just the rows
**With scalar integers.**
df.iloc[0, 1]
2
**With lists of integers.**
df.iloc[[0, 2], [1, 3]]
b d
0 2 4
2 2000 4000
**With slice objects.**
df.iloc[1:3, 0:3]
a b c
1 100 200 300
2 1000 2000 3000
**With a boolean array whose length matches the columns.**
df.iloc[:, [True, False, True, False]]
a c
0 1 3
1 100 300
2 1000 3000
**With a callable function that expects the Series or DataFrame.**
df.iloc[:, lambda df: [0, 2]]
a c
0 1 3
1 100 300
2 1000 3000
实践
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}]
df = pd.DataFrame(mydict)
#获取指定行
index0 =df.iloc[0]
print("first rows",index0)
#获取多行
index01=df.iloc[:2]
print("some rows",index01)
#使用lambda 函数挑选满足指定条件的行
selectDf=df.loc[lambda x :x['a']==100]
print(selectDf)
selectDf = df[df['a']==1000]
print(selectDf)
#使用iloc 将bool 转换为整数index
bool_array = df['a'] == 1
print(bool_array)
indices = bool_array[bool_array].index
print(indices)
selectDf=df.iloc[indices]
print(selectDf)
#使用bool数组
print(df.iloc[[True, False, True]])