将 Pandas DataFrame 写入带有一些空行的 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20665141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a pandas DataFrame into a csv file with some empty rows
提问by user1242808
I create a one-column pandas DataFrame that contains only strings. One row is empty. When I write the file on disk, the empty row gets an empty quote "" while I want no quote at all. Here's how to replicate the issue:
我创建了一个仅包含字符串的单列 Pandas DataFrame。一排是空的。当我将文件写入磁盘时,空行会得到一个空引号 "",而我根本不需要引号。以下是重现问题的方法:
import pandas as pd
df = "Name=Test\n\n[Actual Values]\nLength=12\n"
df = pd.DataFrame(df.split("\n"))
df.to_csv("C:/Users/Max/Desktop/Test.txt", header=False, index=False)
The output file should be like this:
输出文件应该是这样的:
Name=Test
[Actual Values]
Length=12
But instead is like this:
但相反是这样的:
Name=Test
[Actual Values]
""
Length=12
Is there a way to instruct pandas not to write the quotes and leaves an empty row in the output text file? Thank you, a lot.
有没有办法指示Pandas不要写引号并在输出文本文件中留下空行?非常感谢。
回答by aensm
There is a parameter for DataFrame.to_csv called na_rep. If you have Nonevalues, it will replace them with whatever you pass into this field.
DataFrame.to_csv 有一个名为 na_rep 的参数。如果您有None值,它将用您传递到此字段的任何内容替换它们。
import pandas as pd
df = "Name=Test\n"
df += "\n[Actual Values]\n"
df += "Length=12\n"
df = pd.DataFrame(df.split("\n"))
df[df[0]==""] = None
df.to_csv("pandas_test.txt", header=False, index=False, na_rep=" ")
Unfortunately, it looks like passing in na_rep=""will print quotes into the csv. However, if you pass in a single space (na_rep=" ") it looks better aesthetically...
不幸的是,看起来传入na_rep=""会将引号打印到 csv 中。但是,如果您传入一个空格 ( na_rep=" "),它在美学上看起来会更好……
Of course you could always write your own function to output a csv, or simply replace the "" in the output file using:
当然,您始终可以编写自己的函数来输出 csv,或者只需使用以下命令替换输出文件中的“”:
f = open(filename, 'r')
text = f.read()
f.close()
text = text.replace("\"\"","")
f = open(filename, 'w')
f.write(text)
f.close()
And here's how you could write your own to_csv()method:
以下是您如何编写自己的to_csv()方法:
def to_csv(df, filename, separator):
f = open(filename, 'w')
for col in df.values:
for row in col:
f.write(row + separator)
f.close()

