这个错误通常是因为索引超出范围引起的。可能是因为你的数据框中没有第3列,或者第3列的索引是从0开始的,而你的代码中使用的索引是从1开始的。

你可以尝试以下方法来解决问题:

  1. 打印数据框的形状和列名: 使用 print(x.shape)print(x.columns) 来查看数据框的维度和列名,确认是否存在第3列。
  2. 使用 iloc 进行列提取: x.iloc[:, 2] 提取第3列,其中 : 表示提取所有行,2 表示提取第3列。

示例代码:

import pandas as pd

# 读取 CSV 文件
stock_sales = pd.read_csv(
    comp_dir / 'train.csv',
    usecols=['Data_ID', 'Time', 'Close_Price'],
    dtype={
        'Data_ID': 'int',
        #'Time': 'datetime64',
        'Close_Price': 'float32',
    },
    parse_dates=['Time'],
    infer_datetime_format=True,
)

x = stock_sales.copy

# 提取第3列
third_column = x.iloc[:, 2]

注意: 索引是从0开始的,所以第3列的索引为 2。

通过以上步骤,您应该能够解决'single positional indexer is out-of-bounds' 错误,并成功提取数据框中的第3列。

解决'single positional indexer is out-of-bounds' 错误的Python Pandas教程

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

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