python – pandas转义回车到to_csv
发布时间:2020-11-18 10:37:37 所属栏目:Python 来源:互联网
导读:我有一个字符串列,有时在字符串中有回车符: import pandas as pdfrom io import StringIOdatastring = StringIO(country metric 2011 2012USA GDP 7 4USA Pop. 2
我有一个字符串列,有时在字符串中有回车符: import pandas as pd from io import StringIO datastring = StringIO(""" country metric 2011 2012 USA GDP 7 4 USA Pop. 2 3 GB GDP 8 7 """) df = pd.read_table(datastring,sep='ss+') df.metric = df.metric + 'r' # append carriage return print(df) country metric 2011 2012 0 USA GDPr 7 4 1 USA Pop.r 2 3 2 GB GDPr 8 7 在写入和读取csv时,数据框被破坏: df.to_csv('data.csv',index=None) print(pd.read_csv('data.csv')) country metric 2011 2012 0 USA GDP NaN NaN 1 NaN 7 4 NaN 2 USA Pop. NaN NaN 3 NaN 2 3 NaN 4 GB GDP NaN NaN 5 NaN 8 7 NaN 题 解决这个问题的最佳方法是什么?一个显而易见的方法是首先清理数据 df.metric = df.metric.str.replace('r','') 解决方法指定lineterminator:print(pd.read_csv('data.csv',lineterminator='n')) country metric 2011 2012 0 USA GDPr 7 4 1 USA Pop.r 2 3 2 GB GDPr 8 7 (编辑:十堰站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 一些Python中的二维数组的操作方法
- 在Python的Cmd.cmd中完成filename tab-completion
- TypeError:’function’对象不可订阅 – Python
- dict.viewkeys()返回的数据类型是什么? [python 2.7]
- python – Matplotlib显示多个图像与for循环
- python – 从appengine应用程序上传文件到谷歌云存储
- python – 使用Numpy stride_tricks获取非重叠的数组块
- 在Python中开发时保护MySQL密码?
- Python更改接口通道
- python – TensorFlow:SKCompat折旧警告