Pandas iloc 函数

'iloc'('integer location' 的缩写)是 Pandas 库中的一个函数,用于根据位置索引来访问数据框中的数据。与 'loc' 函数不同,'iloc' 函数使用整数位置而不是标签来选择数据。

语法:

df.iloc[row_index, column_index]

其中,'row_index' 和 'column_index' 可以是单个整数、整数列表、整数切片或布尔数组。

  • 如果只指定 'row_index',那么将返回整个行。
  • 如果只指定 'column_index',那么将返回整个列。
  • 如果同时指定 'row_index' 和 'column_index',那么将返回指定行列位置的单个数据。

示例:

import pandas as pd

data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
        'age': [25, 32, 18, 47, 22],
        'gender': ['F', 'M', 'M', 'M', 'F']}
df = pd.DataFrame(data)
  • 选择第 2 行、第 1 列的数据:
df.iloc[1, 0]  # 返回 'Bob'
  • 选择第 2、3、4 行的数据:
df.iloc[1:4, :]  # 返回第 2、3、4 行的所有列

总结:

'iloc' 函数是一个非常有用的函数,可以根据位置索引来选择数据框中的数据,对于数据分析和数据处理非常有帮助。

Pandas iloc 函数:使用整数位置索引访问数据

原文地址: https://www.cveoy.top/t/topic/oehQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录