Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除矩阵中的多行_Python_Python 2.7_Matrix - Fatal编程技术网

Python 删除矩阵中的多行

Python 删除矩阵中的多行,python,python-2.7,matrix,Python,Python 2.7,Matrix,我正在编写一个程序,从CSV中获取数据,并将其转换为一个表,然后导出为PDF。我正在使用的CSV有一堆空行,所以当我用Python创建矩阵时,我有一堆空行。我想删除以开头的所有行。我写的代码是: i=0 x=rows-empty ##where empty has been defined and the number of rows I need to delete. for i in range(x): if Matrix[i][0] == '': del Matri

我正在编写一个程序,从CSV中获取数据,并将其转换为一个表,然后导出为PDF。我正在使用的CSV有一堆空行,所以当我用Python创建矩阵时,我有一堆空行。我想删除以开头的所有行。我写的代码是:

i=0
x=rows-empty ##where empty has been defined and the number of rows I need to delete.
for i in range(x):
    if Matrix[i][0] == '':
        del Matrix[i]
    i+=1
我遇到的问题是,如果有两个连续的空行,只有一行被删除。有没有办法摆脱这两条线

我使用以下代码创建并填充矩阵:

##creates empty matrix
with open(filename) as csvfile:
serverinfo=csv.reader(csvfile, delimiter=",", quotechar="|")
rows=0

for row in serverinfo:    
    NumColumns = len(row)        
    rows += 1

Matrix=[[0 for x in xrange(9)] for x in xrange(rows)]  
csvfile.close()

##fills Matrix
with open(filename) as csvfile:
serverinfo=csv.reader(csvfile, delimiter=",", quotechar="|")
rows=0

for row in serverinfo:
    colnum = 0
    for col in row:
        Matrix[rows][colnum] = col
        if col==0:
            del col
        colnum += 1
    rows += 1
csvfile.close()

与其在之后删除它们,不如先不加载它们。您还可以通过快捷方式重新读取文件两次,因为您似乎设置了9的列限制,所以对于每一行,只需用0填充到该大小即可。。。。例如:

import csv
from itertools import chain, islice, repeat

COLS = 9 # or pre-scan file to get max columns
FILL_VALUE = 0 # or None, or blank for instance
with open(filename) as fin:
    csvin = csv.reader(fin) # use appropriate delimiter/dialect settings
    non_blanks = (row for row in csvin if row[0]) # filter out rows with blank 1st col
    matrix = [list(islice(chain(row, repeat(FILL_VALUE)), COLS)) for row in non_blanks] 

根据您对数据所做的操作,您可能还希望查看numpy模块和可用的loadtxt方法。

您如何读取/加载CSV文件?什么是矩阵-我们正在处理numpy等。。。