python - IndexError : index 261861 is out of bounds for axis 0 with size 169567

标签 python matrix indexing error-handling vcf-vcard

我是编程的初学者,但遇到以下问题:
我想写一个定义,在其中创建一个空矩阵,将选定染色体的数据从vcf文件(使用pyvcf)中创建出来。正确创建了空矩阵。

IndexError:索引261861超出轴0的范围,大小为169567

但是,如果我尝试将第二条染色体作为输入,则会发生上述错误。第一条染色体以索引号262860结尾,这就是为什么我认为它想以某种方式将该行的数据放置在矩阵的此行中,但是我不明白为什么!

这是我的代码:

def creatematrix(newfile):

'''Based on the choice of a chromosome, this function fetches the positions and the DP values out of the vcf and saves it in a matrix.'''

    vcf_reader = vcf.Reader(open(newfile), 'r')
    numpos=0
    Chr=input("Chromosome: ")
    with open(newfile,'r') as newerfile: 
        for line in newerfile: 
            if line.startswith(Chr):
                numpos=numpos+1

    matrix = np.zeros(shape=(numpos,6)) -> here i am creating the matrix with so much lines as lines are in the vcf for the chosen chromosome (numpos)

    z=0
    for rec in vcf_reader:
        if rec.CHROM==Chr:
            matrix[z,0]=rec.CHROM
            matrix[z,1]=rec.POS 
            for samples in rec.samples:
                matrix[z,2]=samples['GT']
                matrix[z,3]=samples['DP']
        z=z+1 

我真的希望有人可以帮助我!

问候,
米莱娜

最佳答案

您正在为vcf_reader中的每一行加z,而仅在确定了所需染色体后才想这样做。

只需将z = z + 1放入if语句中即可完成以下操作:

z=0
for rec in vcf_reader:
    if rec.CHROM==Chr:
        matrix[z,0]=rec.CHROM
        matrix[z,1]=rec.POS 
        for samples in rec.samples:   # You might want to check this for loop as well. Now you are overwriting matrix[z, 2] and matrix[z, 3] everytime so you only save the last samples?
            matrix[z,2]=samples['GT']
            matrix[z,3]=samples['DP']
        z=z+1 # z now only increases when the matched chromosome is found.

关于python - IndexError : index 261861 is out of bounds for axis 0 with size 169567,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51522878/

相关文章:

python - 正确使用 fmin_l_bfgs_b 来拟合模型参数

r - 基于行和列总和的 0 和 1 条件随机矩阵

c - 将两个不同维度的矩阵相乘

linux - 追踪器还是召回器?

python - Numpy:如何添加/加入切片对象?

python - 使用滚动背景时按住空格键或向下键后 Sprite 会消失

python - 使用 Seaborn 和 Statsmodels 在一个图中显示数据和模型预测

Python Pandas - 连接两个具有不同行数和列数的数据框

c - 动态分配矩阵的函数

python - 使用方括号访问 Pandas 列与使用点(如属性)