【问题标题】:Remove cell in a CSV file if a certain value is there如果存在某个值,则删除 CSV 文件中的单元格
【发布时间】:2013-07-22 04:44:41
【问题描述】:

我有两种类型的 CSV 文件,我想将它们合并在一起。 为此,我想在每一行中找到某些值并在它们存在时将其删除。

我尝试使用 list.Indexlist.Remove 函数,但当值不在特定文件中时出现错误。

例如,这两行是(为了更好的显示,我剪掉了其余的行):

CSV 1950    1300    1180    48  48  400 2   PASS        0   51:31.5
CSV 3270    2500    1950    1300    1180                        48

我想定位具有“3270”和“2500”值的单元格,以便两个文件对齐... 之后我想再次删除 空单元格 - 它们将对齐...

你能帮我理解一下这样做的方法吗?

谢谢, 尼姆罗德。

【问题讨论】:

  • 你是如何对齐文件的?您是否使用32702500 前两个来制作单元格并删除之前的所有内容?他们会一直是32702500吗?
  • CSV 文件的顶部是否有一行包含列名?
  • 文件中的前几行可能不同...数据行是相同的,除了一种类型的文件具有而另一种类型的文件没有的几个单元格。 - 例如。 3270 和另一个值位于一种类型的文件中,而不是另一种类型的文件中
  • 您能否提供更广泛的数据样本?另外,第一行不是缺失值而不是第二行;比如,是什么决定了任何给定的行应该被“拉”到左边还是右边?
  • Dilber,我不确定是什么混乱......我要做的就是遍历一行,如果它的值为“3270” - 删除它。这在python中是不可能的吗??

标签: python list parsing csv indexing


【解决方案1】:

很难确切地说出你希望完成什么,但我认为这应该让你开始。

#!/usr/bin/env python

import csv    

myfile = '/path/to/untitled.csv'
newfile = '/path/to/untitled_new.csv'

reader = csv.reader(open(myfile))

remove_me = {'3270','2500'}

print('Before:')
print(open(myfile).read())

for row in reader:
    new_row = []
    for column in row:
        if column not in remove_me:
            new_row.append(column)

    csv.writer(open(newfile,'a')).writerow(new_row)

print('\n\n')
print('After:')
print(open(newfile).read())

输出:

Before:
1950,1300,1180,48,48,400
3270,2500,1950,1300,1180



After:
1950,1300,1180,48,48,400 
1950,1300,1180 

确保在迭代同一个列表时没有使用 list.remove,否则您可能会搞砸自己。我上面的代码使用了一种更安全的策略,将通过 if 测试的值(列不是您想要摆脱的值之一)复制到新列表中,然后编写新的列表到一个新的 .csv 文件。

这或多或少是你打算做的吗?

要删除空白单元格,我想您可以将 '' 添加到 remove_me

【讨论】:

  • 我喜欢你的方式。我做了以下解决它:if NewRow[1]=='3270': del NewRow[1:3] del NewRow[4:9] del NewRow[6]
【解决方案2】:

我建议你循环文件中的每个值,然后设置一些条件删除元素,然后将值合并到一个新的输出文件中

Step1 读取文件

import sys
import csv
updatedlist = []
for val in csv.reader(open('input1.csv' , 'rb')) :
    print val

## val will be a list of each row , 
## So in this case you will have to 
## select the elements while you will be looping 
## then replace or removing the elements you want to remove
## and make a new updated list which you will then have 
## to append to a new output.csv file
## then do the same the to the other file and append to the output.csv file    


for Values  in  updatedlist :

##looping thru the values and then make a string of the values separated by commas
        f  = open('output.csv' , 'a')
        f.writelines(updatestring) ##updated list with a string of comma separated values 
        f.close()

【讨论】:

    猜你喜欢
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多