2017-01-31 21 views
1

我想從包含不同列但不帶分隔符的csv文件創建數據框。看起來,列條目之間只有不同數量的空格。如何創建一個沒有分隔符的CSV格式的熊貓數據框(在Python中)

另外,csv頂部有一些標題行,其中包含自述文件信息,沒有任何列。

我有麻煩pd.read_csv這樣做()

謝謝!

文件看起來是這樣的:

This is a header of the textfile.The header has no columns. 
This is a header of the textfile.The header has no columns. 
This is a header of the textfile.The header has no columns. 

... 
P-X1-6030-07-A01 368963 
P-X1-6030-08-A01 368964 
P-X1-6030-09-A01 368965 
P-A-1-1011-14-G-01 368967 
P-A-1-1014-01-G-05 368968 
P-A-1-1017-02-D-01 368969 
... 
+0

'pd.read_fwf(filename,header = None,skiprows = N)',您必須將N設置爲「無趣行數」 – MaxU

回答

3

假設你有以下數據文件:

This is a header of the textfile.The header has no columns. 
This is a header of the textfile.The header has no columns. 
This is a header of the textfile.The header has no columns. 

P X1 6030-07-A01 368963 
P-X1-6030-07-A01 368963 
P-X1-6030-08-A01 368964 
P-X1-6030-09-A01 368965 
P-A-1-1011-14-G-01 368967 
P-A-1-1014-01-G-05 368968 
P-A-1-1017-02-D-01 368969 

解決方案:讓我們使用read_fwf()方法:

In [192]: fn = r'D:\temp\.data\data.fwf' 

In [193]: pd.read_fwf(fn, widths=[19, 7], skiprows=4, header=None) 
Out[193]: 
        0  1 
0 P X1 6030-07-A01 368963 # NOTE: first column has spaces ... 
1 P-X1-6030-07-A01 368963 
2 P-X1-6030-08-A01 368964 
3 P-X1-6030-09-A01 368965 
4 P-A-1-1011-14-G-01 368967 
5 P-A-1-1014-01-G-05 368968 
6 P-A-1-1017-02-D-01 368969 
0
pd.read_csv(filename, delim_whitespace=True, skiprows = number of rows to skip) 
+0

謝謝。不幸的是,這是行不通的。我沒有說:有時第一列還包含空格,也就是說它可能像 P X1 6030-07-A01 368963 這可能是問題的根源嗎? –

相關問題