[英]to extract specific columns from a csv file and copy it to another using python
I have a CSV file which is actually a matrix of 0's and 1's. 我有一个CSV文件,它实际上是0和1的矩阵。 I need to exclude those columns that have 0's and pick only those that have 1's and copy them to another CSV file. 我需要排除那些具有0的列,只选择那些具有1的列,然后将它们复制到另一个CSV文件中。
Here is what I have tried: 这是我尝试过的:
reader=csv.DictReader(open("test1.csv","r"),[])
for data in reader:
if data==1:
print data
What am I doing wrong? 我究竟做错了什么?
reader = csv.DictReader(open("test1.csv", "r"), [])
for data in reader:
if data[column header] != 0:
print data[column header]
If you need to exclude all columns that have any zeroes in them, then first you need to read the whole file in memory -- because only after having seen every row will you know which columns have any zeroes! 如果您需要排除有任何零在他们的所有列,那么首先你需要读取内存中的整个文件-因为只有在看到每一行,你会知道哪些列有任何零后! This is a logical need -- whatever language you use the need will remain, it's intrinsic to the problem 这是合乎逻辑的需求-无论您使用哪种需求的语言都会保留下来,这是问题的内在原因
So, for example: 因此,例如:
allrows = list(reader)
Now, allrows
is a list of dictionaries, whose items are strings, presumably 0
or 1
. 现在, allrows
是一个词典列表,其项目为字符串,大概为0
或1
。 Now, you could do: 现在,您可以执行以下操作:
keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]
...not the fastest approach, but hopefully very, very simple to understand! ...不是最快的方法,但希望非常容易理解!
Once you do know which columns you want to keep, prepare a DictWriter
instance w
with those columns as the headers and the extrasaction='ignore'
argument (so it will ignore "extra" keys in the dicts passed to it, and finally 一旦知道要保留的列,就准备一个DictWriter
实例w
,将这些列作为标题,并使用extrasaction='ignore'
参数(这样它将忽略传递给它的字典中的“ extra”键,最后
w.writerows(allrows)
If you mean something different than "exclude all columns which have any zeroes in them", then please clarify exactly what you do mean by "i need exclude those columns that have 0's" because I can't interpret it differently. 如果您的意思不同于“排除其中包含零的所有列”,那么请明确说明您的意思是“我需要排除那些具有0的列”,因为我无法以不同的方式解释它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.