如何在Python中使用pandas模块读取“\n\n”?

3

有一个数据文件,在每行结尾都有\n\n
http://pan.baidu.com/s/1o6jq5q6
我的系统环境:win7+python3.3+R-3.0.3
在R语言中:

sessionInfo()

[1] LC_COLLATE=Chinese (Simplified)_People's Republic of China.936 
[2] LC_CTYPE=Chinese (Simplified)_People's Republic of China.936   
[3] LC_MONETARY=Chinese (Simplified)_People's Republic of China.936
[4] LC_NUMERIC=C                                                   
[5] LC_TIME=Chinese (Simplified)_People's Republic of China.936    

在Python中: chcp 936
我可以在R中读取它。
read.table("test.pandas",sep=",",header=TRUE)

这很简单。

而且我可以在Python中读取它,以获得几乎相同的输出。

fr=open("g:\\test.pandas","r",encoding="gbk").read()
data=[x for x in fr.splitlines() if x.strip() !=""]
for id,char in enumerate(data):
    print(str(id)+","+char)

当我在Python模块pandas中阅读时,
import pandas as pd
pd.read_csv("test.pandas",sep=",",encoding="gbk")

我在输出中发现了两个问题:
1)如何进行正确对齐(我已在其他帖子中提出此问题)
如何在Python中使用非ANSI字符设置pandas中的对齐
2)每个实际数据中都有一个NaN行。
我能否改进我的pandas代码以在控制台中获得更好的显示?
enter image description here
enter image description here
enter image description here
1个回答

2

当你使用open('test.pandas', 'rb')读取文件时,发现它的行结束符是'\r\r\n'。Python 3.3将其转换为'\n\n',而Python 2.7则在用open('test.pandas', 'r', encoding='gbk')读取时将其转换为'\r\n'。

pandas.read_csv有一个lineterminator参数,但它只接受单个字符的终止符。

你可以在将文件传递给pandas.read_csv()之前对其进行一些处理,你可以使用StringIO将字符串缓冲区包装在文件接口中,这样就不需要先写出临时文件了。

import pandas as pd
from io import StringIO

with open('test.pandas', 'r', encoding='gbk') as in_file:
    contents = in_file.read().replace('\n\n', '\n')

df = pd.read_csv(StringIO(contents))

以下输出没有GBK字符集。

>>> df[0:10]
          ??????? ???    ????????
0    HuangTianhui  ??  1948/05/28
1          ??????   ?  1952/03/27
2             ???   ?  1994/12/09
3        LuiChing   ?  1969/08/02
4            ????  ??  1982/03/01
5            ????  ??  1983/08/03
6      YangJiabao   ?  1988/08/25
7  ??????????????  ??  1979/07/10
8          ??????   ?  1949/10/20
9           ???»?   ?  1951/10/21

在Python 2.7中,StringIO()位于模块StringIO而不是io中。

1
我遇到了与“to_html”输出中相同的问题,所以感谢您的帖子。但是,在“contents = contents.replace('\ n \ n','\ n')”上我得到了“AttributeError:'file' object has no attribute 'replace'”。 - iNoob
是的,一样。你至少应该检查一下你的代码是否可行。 - novice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接