这个错误表示您尝试使用索引器访问的列索引超出了 DataFrame 的列范围。您可以检查一下 DataFrame 的列数以及您尝试访问的列的索引位置是否正确。另外,您在代码中没有调用 copy() 方法,应该调用 copy() 方法来复制 DataFrame。以下是您可以尝试的代码:

import pandas as pd
from pathlib import Path

comp_dir = Path('/path/to/your/data')

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,
)
stock_sales['Time'] = stock_sales.Time.dt.to_period('T')
stock_sales = stock_sales.set_index(['Data_ID', 'Time', 'Close_Price']).sort_index()

# 使用 copy() 方法复制 DataFrame
x = stock_sales.copy()

# 检查 DataFrame 的列数
print(x.shape[1])

# 检查您要访问的列的索引位置是否正确
third_column = x.iloc[:, 2]
print(third_column)
Pandas DataFrame 索引超出范围错误:single positional indexer is out-of-bounds

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

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