【问题标题】:"IndexError: single positional indexer is out-of-bounds" in reading file读取文件中的“IndexError:单个位置索引器越界”
【发布时间】:2020-08-18 04:40:21
【问题描述】:

我发现这种问题已经被问过很多次了,但我没有像我这样简单的案例:(

我有一个 test.txt 文件

1 2 3
4 5 6 
7 8 9

我编写了以下 Python 代码

import pandas as pd
import csv
file_0 = 'test.txt'
a0 = pd.read_csv(file_0, header = None)
#a0_df = pd.DataFrame(a0)
print(a0)
print(a0.iloc[:,1])

它会导致以下错误消息

    raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds

我想得到2 5 8,哪里出错了?

【问题讨论】:

  • 也许它在一列中读取了整个1 2 3,尝试指定分隔符..

标签: python python-3.x pandas


【解决方案1】:

首先,您不需要import csv,因为您不使用该模块。

其次,你的文件不是一个逗号-分隔的值。它是 空格 分隔的。你必须告诉读者:

a0 = pd.read_csv(file_0, sep="\s+", header = None)

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2017-09-30
    • 2021-04-17
    相关资源
    最近更新 更多