使用pandas将txt文件处理为csv

时间:2018-03-18 17:09:35

标签: python pandas numpy machine-learning

我有一个波士顿房价的txt文件,我已经从存档UCI机器学习中复制了它,因为数据集不再可用,它看起来像这样:

 0.00632  18.00   2.310  0  0.5380  6.5750  65.20  4.0900   1  296.0  15.30 396.90   4.98  24.00
 0.02731   0.00   7.070  0  0.4690  6.4210  78.90  4.9671   2  242.0  17.80 396.90   9.14  21.60
 0.02729   0.00   7.070  0  0.4690  7.1850  61.10  4.9671   2  242.0  17.80 392.83   4.03  34.70
 0.03237   0.00   2.180  0  0.4580  6.9980  45.80  6.0622   3  222.0  18.70 394.63   2.94  33.40
 0.06905   0.00   2.180  0  0.4580  7.1470  54.20  6.0622   3  222.0  18.70 396.90   5.33  36.20
 0.02985   0.00   2.180  0  0.4580  6.4300  58.70  6.0622   3  222.0  18.70 394.12   5.21  28.70
 0.08829  12.50   7.870  0  0.5240  6.0120  66.60  5.5605   5  311.0  15.20 395.60  12.43  22.90

由于没有分隔符选项(标签,逗号,空格),我分隔并将其粘贴到MS Excel,因此我可以将其 csv 文件,有没有简单的代码,所以我可以通过pandas或numpy快速处理它

1 个答案:

答案 0 :(得分:2)

我认为__init__需要使用txtheader=None也需要使用read_csv的新标头来写入文件:

df = pd.read_csv('file.txt', delim_whitespace=True, header=None)
df.to_csv('file1.txt', index=False, header=None)

或者:

df = pd.read_csv('file.txt', sep='\s+', header=None)
df.to_csv('file1.txt', index=False, header=None)