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:

  1. Select a single element from the options available.
  2. Access the DataFrame element at the specified row and column indices using iloc.
  3. Select multiple elements.
  4. Retrieve elements from the DataFrame starting from row ‘start_row’ to ‘end_row’, and from column ‘start_col’ to ‘end_col’.
  5. Choose a specific line:
  6. Select the rows with the indices specified in the ‘row_indices’ variable from the DataFrame ‘df’.
  7. Select a specific column.
  8. Select all rows and specific columns using their indices in the DataFrame.
  9. Select a combination of rows and columns.
  10. Select the elements in the DataFrame at the specified row and column indices.
  11. Selecting elements using boolean indexing:
  12. 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.

广告
Closing in 10 seconds
bannerAds