Pandas将“\ r”添加到csv文件中

时间:2017-11-20 00:34:35

标签: python python-3.x pandas csv

这归结为一个更简单的问题here

我有一个像这样的pandas数据框:

In [1]: df
Out[1]:
   0        1
0  a  A\nB\nC
1  a  D\nE\nF
2  b  A\nB\nC

当我将它写入csv文件然后读回来时,我希望有相同的数据帧。事实并非如此:

In [2]: df.to_csv("out.csv")

In [3]: df = pd.read_csv("out.csv", index_col=0)

In [4]: df
Out[4]:
   0            1
0  a  A\r\nB\r\nC
1  a  D\r\nE\r\nF
2  b  A\r\nB\r\nC

在每个\r之前添加\n个字符。再次写作和阅读,同样的事情发生了:

In [5]: df.to_csv("out.csv")

In [6]: df = pd.read_csv("out.csv", index_col=0)

In [7]: df
Out[7]:
   0                1
0  a  A\r\r\nB\r\r\nC
1  a  D\r\r\nE\r\r\nF
2  b  A\r\r\nB\r\r\nC

如何阻止pandas添加\r字符?

编辑:
是的我在窗户上。

<小时/> pd.read_csv(pd.compat.StringIO(df.to_csv(index=False)))给了我相同的数据帧,所以问题似乎是写入文件 以二进制模式传递打开的文件对象,如下所示:

with open("out.csv", "wb") as file:
    df.to_csv(file)

结果:

TypeError                                 Traceback (most recent call last)
<ipython-input-20-f31d52fb2ce3> in <module>()
      1 with open("out.csv", "wb") as file:
----> 2     df.to_csv(file)
      3

C:\Program Files\Anaconda3\lib\site-packages\pandas\core\frame.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote, escapechar, decimal, **kwds)
   1342                                      doublequote=doublequote,
   1343                                      escapechar=escapechar, decimal=decimal)
-> 1344         formatter.save()
   1345
   1346         if path_or_buf is None:

C:\Program Files\Anaconda3\lib\site-packages\pandas\formats\format.py in save(self)
   1549
   1550             else:
-> 1551                 self._save()
   1552
   1553         finally:

C:\Program Files\Anaconda3\lib\site-packages\pandas\formats\format.py in _save(self)
   1636     def _save(self):
   1637
-> 1638         self._save_header()
   1639
   1640         nrows = len(self.data_index)

C:\Program Files\Anaconda3\lib\site-packages\pandas\formats\format.py in _save_header(self)
   1632
   1633         # write out the index label line
-> 1634         writer.writerow(encoded_labels)
   1635
   1636     def _save(self):

TypeError: a bytes-like object is required, not 'str'

<小时/> 使用常规写入无效

In [1]: with open("out.csv", "w") as file:
   ...:     df.to_csv(file)
   ...:

In [2]: df = pd.read_csv("out.csv")

In [3]: df
Out[3]:
   Unnamed: 0  0            1
0           0  a  A\r\nB\r\nC
1           1  a  D\r\nE\r\nF
2           2  b  A\r\nB\r\nC

<小时/> 我的python版本是Python 3.5.2 :: Anaconda 4.2.0 (64-bit) 我已确定问题出在pandas.read_csv而不是pandas.to_csv

In [1]: df
Out[1]:
   0        1
0  a  A\nB\nC
1  a  D\nE\nF
2  b  A\nB\nC

In [2]: df.to_csv("out.csv")

In [3]: with open("out.csv", "r") as file:
    ...:     s = file.read()
    ...:

In [4]: s  # Only to_csv has been used, no \r's!
Out[4]: ',0,1\n0,a,"A\nB\nC"\n1,a,"D\nE\nF"\n2,b,"A\nB\nC"\n'

In [5]: pd.read_csv("out.csv")  # Now the \r's come in
Out[5]:
   Unnamed: 0  0            1
0           0  a  A\r\nB\r\nC
1           1  a  D\r\nE\r\nF
2           2  b  A\r\nB\r\nC

1 个答案:

答案 0 :(得分:3)

正如有些人已经在上面的评论和帖子here中提到的那样,这是序列化换行符时的典型窗口问题。 pandas-dev github #17365也报告了这个问题。

希望在Python3上,您可以指定换行符:

with open("out.csv", mode='w', newline='\n') as f:
    df.to_csv(f, sep=",", line_terminator='\n', encoding='utf-8')