用字符串替换空白值

时间:2020-07-11 01:18:25

标签: python pandas csv

我需要以某种方式处理一个csv文件,以进入csv文件,在我的示例csv文件中查找c0-c5之间的空白字段。使用csv文件哪里有空格,我想用我想要的任何用语替换空格,例如“找不到”

到目前为止,我唯一要编写的代码就是删除我不需要的列,但是我需要的操作确实找不到任何东西。也许这不可能吗?

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

#!/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

2 个答案:

答案 0 :(得分:1)

或者考虑您的“注释问题”(如果您不一定像n1colas.m的答案那样使用熊猫),请使用字符串替换和 只需使用:

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)进行此类替换,而不要像您的问题所示那样写入您的infile中。检查它是否满足您的要求。然后只覆盖您的文件。乍一看似乎没有必要,但是会发生错误...

答案 1 :(得分:0)

您必须执行此行

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)

我建议将数据变量更改为其他名称,因为您的列具有相同的名称并且可能会造成混淆。