Detailed usage of iloc in Python
In Python, iloc is a function in the pandas library that is used to select data based on integer location. It can select rows and columns using integer indexes or slices.
Below is a usage of iloc:
- Select a single element from the options available.
- Access the DataFrame element at the specified row and column indices using iloc.
- Select multiple elements.
- Retrieve elements from the DataFrame starting from row ‘start_row’ to ‘end_row’, and from column ‘start_col’ to ‘end_col’.
- Choose a specific line:
- Select the rows with the indices specified in the ‘row_indices’ variable from the DataFrame ‘df’.
- Select a specific column.
- Select all rows and specific columns using their indices in the DataFrame.
- Select a combination of rows and columns.
- Select the elements in the DataFrame at the specified row and column indices.
- Selecting elements using boolean indexing:
- Return the rows in the DataFrame based on the boolean indexing.
It should be noted that the indices in the iloc function are zero-based, meaning the index of the first element is 0.
Here are some examples:
import pandas as pd
# 创建一个DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# 选择特定行和列的元素
element = df.iloc[1, 2]
print(element) # 输出结果为 8
# 选择多行和多列的元素
subset = df.iloc[0:2, 1:3]
print(subset)
# 输出结果为:
# B C
# 0 4 7
# 1 5 8
# 选择特定的行和列
rows = [0, 2]
cols = [1, 2]
subset = df.iloc[rows, cols]
print(subset)
# 输出结果为:
# B C
# 0 4 7
# 2 6 9
# 使用布尔索引选择元素
boolean_index = df > 5
subset = df.iloc[boolean_index]
print(subset)
# 输出结果为:
# A B C
# 0 NaN NaN 7.0
# 1 NaN NaN 8.0
# 2 NaN 6.0 9.0
These examples demonstrate the basic usage of the iloc function, which you can adjust according to your own needs.