python - 用零替换空的 csv 列值

标签 python csv list

所以我正在处理一个包含缺失值的 csv 文件。 我想要我的脚本是:

#!/usr/bin/python

import csv
import sys

#1. Place each record of a file in a list.
#2. Iterate thru each element of the list and get its length.
#3. If the length is less than one replace with value x.


reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
    for x in row[:]:
                if len(x)< 1:
                         x = 0
                print x
print row

这是一个数据示例,我试了一下,理想情况下它应该适用于任何列长度

Before:
actnum,col2,col4
xxxxx ,    ,
xxxxx , 845   ,
xxxxx ,    ,545

After
actnum,col2,col4
xxxxx , 0  , 0
xxxxx , 845, 0
xxxxx , 0  ,545

任何指导将不胜感激

更新这是我现在拥有的(谢谢):

reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
    for i, x in enumerate(row):
                if len(x)< 1:
                         x = row[i] = 0
print row

但是它似乎只输出了一条记录,我将在命令行上将输出通过管道传输到一个新文件。

更新 3:好的,现在我遇到了相反的问题,我正在输出每条记录的副本。 为什么会这样?

After
actnum,col2,col4
actnum,col2,col4
xxxxx , 0  , 0
xxxxx , 0  , 0
xxxxx , 845, 0
xxxxx , 845, 0
xxxxx , 0  ,545
xxxxx , 0  ,545

好的,我修复了它(如下),谢谢大家的帮助。

#!/usr/bin/python

import csv
import sys

#1. Place each record of a file in a list.
#2. Iterate thru each element of the list and get its length.
#3. If the length is less than one replace with value x.


reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
    for i, x in enumerate(row):
                if len(x)< 1:
                         x = row[i] = 0
    print ','.join(str(x) for x in row)

最佳答案

更改代码:

for row in reader:
    for x in row[:]:
                if len(x)< 1:
                         x = 0
                print x

进入:

for row in reader:
    for i, x in enumerate(row):
                if len(x)< 1:
                         x = row[i] = 0
                print x

不确定您认为通过 print 完成了什么,但关键问题是您需要修改 row,为此您需要一个索引进入其中,enumerate 给你。

另请注意,除了您要更改为数字 0 的空值之外,所有其他值都将保留为字符串。如果您想将它们转换为 int,您必须明确地这样做。

关于python - 用零替换空的 csv 列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2862709/

相关文章:

read.csv 带标题但忽略第二行

r - 如何将 .csv 文件导入 R?

python-3.x - 在新的数据帧上自动提取两个Python字符串之间的相等性

python - 字符串列表在 python 中的转换

python - 对 python 列表执行批量算术运算

python - 使用带有 df.loc == 语句的append() Pandas Python

python - 如何为列表中重复的每个值计算平均值?

python - 无法同时从两个不同深度刮取不同字段

python - 左连接的 SQLAlchemy 错误

c# - Foreach 对象列表中的组项目