【问题标题】:Python Index error (out of bounds) accessing element in 2D arrayPython索引错误(超出范围)访问二维数组中的元素
【发布时间】:2013-08-18 16:06:55
【问题描述】:

我正在尝试访问从 csv 文件中的数据创建的二维数组的元素。我可以很好地打印数组。

当我尝试访问数组以查找某个元素(即来自 'row' 1 'column' 5 的数字)时,它会引发错误:

C:\Users\AClayton\Current\python begin\code_tester.py in create_alldata(whichfile)
37     array_data=np.array(all_data)
---> 38     nb=array_data[1][5]
IndexError: index 1 is out of bounds for axis 0 with size 1

如果有人能帮忙就太好了

def create_alldata(whichfile):
    open_file = open(infile, 'rb')                       
    csv_current=csv.reader(open_file)                     
    all_data=[]                              
    np.array(all_data)
    for row in open_file:         
        all_data.append(row)                            
    open_file.close()
    array_data=np.array(all_data)
    nb=array_data[1][5]
    return array_data,    


path=raw_input('What is the directory?')
for infile in glob.glob(os.path.join(path, '*.csv')): 
    create_alldata(infile)

【问题讨论】:

    标签: python csv numpy multidimensional-array indexoutofboundsexception


    【解决方案1】:

    如果您想从 CSV 读取多维数据,请使用 numpy.genfromtxt()numpy.loadtxt() 函数,具体取决于您的 CSV 文件的完整性(如果行长变化则使用前者,如果行长不变则使用后者)。

    您正在尝试手动构建一个多维 numpy 数组,但您发现它并不像那样工作。

    import numpy
    
    def create_alldata(whichfile):
        return numpy.genfromtxt(whichfile)                     
    

    【讨论】:

    • 谢谢 Martijn,我做了你建议的改变,但它抛出了错误:IndexError: too many indices
    • @AshleighClayton:那么你没有多维 numpy 数组。
    • 我正在尝试使用以下方式访问 2 个列: a = np.array(all_data) col=a[:,[0,1]] ,但是我检索了前两个列?跨度>
    • genfromtxt已经返回一个numpy数组,你为什么还在使用np.array()
    • 目前还不清楚你在问什么。您正在尝试访问 2 列,并且您显示的切片返回前两列,是的。究竟是什么问题?
    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    相关资源
    最近更新 更多