用字符串替换空白值

2024-10-03 09:10:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的示例csv文件中,我需要以进入csv文件的方式操作csv文件,查找c0-c5之间的空白字段。在CSV文件中,如果有空白的话,我想用任何VIDECK来替换空白,比如“没有找到”

到目前为止,我唯一拥有的代码就是删除一个我不需要的列,但是我需要的操作我真的找不到任何东西。。也许这是不可能的

另外,我想知道如何更改列名..谢谢

#!/bin/env python


import pandas
data = pandas.read_csv('report.csv')
data = data.drop(['date',axis=1)
data.to_csv('final_report.csv')

enter image description here


Tags: 文件csv代码reportenv示例pandasdata
2条回答

你必须执行这一行

data['data'] = data['data'].fillna("not found")

这里是文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

这里有一个例子

import pandas
data = pandas.read_csv('final_report.csv')
data.info()
data['data'] = data['data'].fillna("Something")
print(data)

我建议将数据变量更改为其他变量,因为您的列具有相同的名称,可能会令人困惑

或者,考虑到您的“评论问题”(如果您不一定要像n1colas.m的回答那样使用pandas),使用字符串替换和 只需使用以下命令循环您的文件:

with open("modified_file.csv","w") as of:
  with open("report.csv", "r") as inf:
    for line in inf:
     if "#" not in line: # in the case your csv file has a comment marker somewhere and it is called #, the line is skipped, which means you get a clean comma separated value file as the outfile- if you do want to keep such lines simply remove the if condition
       mystring=line.replace(", ,","not_found").replace("data","input") # in case it is not only one blank space you can also use the regex for n times blank space here
       print(mystring, file=of, end=""); # prints the replaced line to outfile and writes no newline

我知道这不是最有效的方法,但可能是一种你很容易理解你在做什么,并且能够根据你内心的愿望修改的方法。 对于任何大小合理的csv文件,它仍然应该几乎在瞬间工作。 此外,出于测试目的,始终使用单独的文件(of)进行替换,而不是像您的问题所述的那样写入填充文件。检查它是否符合你的要求。然后才覆盖你的填充。一开始这似乎不必要,但会发生错误

相关问题 更多 >