![](/img/trans.png)
[英]Python script to check csv columns for empty cells that will be used with multiple excels
[英]How to check for empty cells in csv before converting to int (Python script)?
我是stackoverflow和python的新手,所以如果此问题缺乏详细信息,请原谅我
我想将数据从csv文件导入到Postgres中的表中。 但是,我不确定如何检查空值。 我想将某些值导入为int(由于某种原因,这些值在它们后跟.0,即当我想要10时为10.0)。 但是on_hand和on_order的某些单元格为null
-我将如何检查这些单元格是否为null
以及它们是否为null
,以简单地执行row[2].strip
和row[3].strip
?
for row in reader:
arg = {
'name': row[0].strip(),
'description': row[1].strip(),
'on_hand': int(float(row[2].strip())),
'on_order': int(float(row[3].strip()))
}
cur.execute(
"""INSERT INTO
"Inventory"("Name","Description","On hand","On order")
select %(name)s,
%(description)s,
%(on_hand)s,
%(on_order)s,
WHERE NOT EXISTS (
SELECT * FROM "Inventory" WHERE "Name"=%(name)s
);""", arg)
谢谢!
怎么样-基本上只有在row[2]
实际上有一些值的情况下才转换为float,否则只返回一个空字符串""
(您也可以返回None
)/
for row in reader:
arg = {
'name': row[0].strip(),
'description': row[1].strip(),
'on_hand': int(float(row[2].strip())) if row[2].strip() else "",
'on_order': int(float(row[3].strip())) if row[3].strip() else ""
}
我只是try
进行转换,如果发生ValueError
异常,则将None
分配给变量。
for row in reader:
try:
on_hand = int(float(row[2]))
except ValueError:
on_hand = None
try:
on_order = int(float(row[3]))
except ValueError:
on_order = None
arg = {
'name': row[0].strip(),
'description': row[1].strip(),
'on_hand': on_hand,
'on_order': on_order
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.