pandas 读写 txt 时遇到的两个问题:
1、txt 的分隔符为|,文档使用 gbk 编码,由于解码时存在特殊字符的 encode 后的字符串也有“|”,导致有一些行析出的列长度大于其他长度,因而读取失败;
2、写入时,报错 UnicodeEncodeError: 'gbk' codec can't encode character '\u4dae' in position 151: illegal multibyte sequence
请问大神们,应该怎么搞
语句为:
data = pd.read_table(filename, sep ='|', skiprows=startline, header=None, encoding='gb18030', skip_blank_lines=True, dtype=str, error_bad_lines=False, warn_bad_lines=True)
data.to_csv(fw, index=False, encoding='gb18030', sep='|', header=False)
追加中间对data的操作,其实就是将部分列置为空,然后排序
for l in ln: data.loc[:,l]='' data.sort_values(by=[0,1,2], axis=0, inplace=True)
1 shnj 2018-06-04 13:20:31 +08:00 第一个问题: 如果有问题的行不多且可以舍弃,可以使用 error_bad_lines 参数,ref: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html 第二个问题没遇到过,但是网上有些解决方案,改变标准输出的默认编码应该可以解决。 |
2 chesterzzy 2018-06-04 13:22:48 +08:00 先把 gbk 转为 utf-8 再说。 |
![]() | 3 RicardoScofileld 2018-06-04 13:48:05 +08:00 你指定在 read 的时候,指定 names,这样的话就不会报错了 |
![]() | 5 yeyu1989 OP @chesterzzy 这个怎么转?我附了语句了 |
![]() | 6 yeyu1989 OP @RicardoScofileld names : array-like, default None 是指这个参数么。这个好像是列名? |
7 imzhong 2018-06-04 14:23:53 +08:00 .encode('utf_8') 试试,不行 用.encode('gb18030',errors='replace')把无法处理的字符换成‘?’ |
![]() | 8 RicardoScofileld 2018-06-04 15:02:40 +08:00 @yeyu1989 对 你指定列名就好了 |
![]() | 9 yeyu1989 OP @RicardoScofileld 我使用了参数 header=None,所有列名都是 0,1,2,3 这些好像。有影响吗 |
![]() | 10 flyingghost 2018-06-04 15:49:38 +08:00 sep 参数支持正则表达式。如果你的分隔符和字符串能用某种正则来做区分,那可以把单纯的"|"字符替换成正则来做分割。 第二个问题,这确实不是合法字符啊。最好是搞清楚来源是什么。很有可能是读时就读错了,最好解决掉。否则这行数据有可能是脏的。 |
![]() | 11 RicardoScofileld 2018-06-04 16:40:08 +08:00 @yeyu1989 这是默认生成的,你最好自己指定 |