【问题标题】:IndexError: index 164 is out of bounds for axis 1 with size 164IndexError:索引 164 超出轴 1 的范围,大小为 164
【发布时间】:2018-05-09 22:51:03
【问题描述】:

我尝试删除列和行,然后重置列和行。但是在第三个文件上,我得到了错误:

IndexError:索引 164 超出轴 1 的范围,大小为 164

我文件夹中的文件是167*164,并且在删除后变为95*95

path = r'/home/RESULTS'
allFiles = sorted((glob.glob(path + "/*.csv")))
for file_ in allFiles:
    data = pd.read_csv(file_, header=None)
    data = data.astype(str)
    data = data.apply(lambda x: x.str.replace(',', '.'))
    data = data.astype(float)
    data = data.fillna(value=1)
    data.drop(data.columns[cols_to_drop],axis=1,inplace=True)
    data.drop(data.index[rows_to_drop], inplace=True)
    data = data.reset_index(drop=True)
    data = data.T.reset_index(drop=True).T
    print(file_)

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    我相信您可以简化您的解决方案:

    path =r'/home/RESULTS' 
    allFiles = sorted((glob.glob(path + "/*.csv")))
    for file_ in allFiles:
        #decimal for convert float , to .
        data = pd.read_csv(file_, header=None, decimal=',')
        data = data.fillna(value=1)
        #not necessary select columns and index, also ignore drop non exist values
        data.drop(cols_to_drop,axis=1,inplace=True, errors='ignore')
        data.drop(rows_to_drop, inplace=True, errors='ignore')
        data=data.reset_index(drop=True)
        #assign to columns range - reset columns names
        data.columns = range(len(data.columns))
        print(data)
    

    【讨论】:

    • 数据有问题。 3. 文件仅包含 164 rows,因此不可能删除不存在 165 行(索引计数来自0,所以第一行是0165 行的索引是164
    • 另一个错误?这意味着indexcolumns 中没有164 165 166 值。但解决方案是 data.drop(rows_to_drop, inplace=True, errors='ignore')data.drop(cols_to_drop,axis=1,inplace=True, errors='ignore') 忽略删除不存在的值。
    • 但为什么只来自第三个文件?我相信问题出在列中,因为 data.drop(rows_to_drop,axis=1,inplace=True) data.drop(rows_to_drop, inplace=True) 工作得很好
    • 有这些索引。它适用于前两个文件,但第三个是这个错误
    • 我明白了。检查3.文件,您认为列数较少,因此引发错误。也可以在删除 print (data.columns.tolist()) 之前检查列名
    猜你喜欢
    • 2015-08-06
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2020-01-16
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多