Reputation: 618
I have a .asc file where each line has 655 entries and looks somewhat like the following (note the leading whitespace)
-999 -999 -999 -999 -999 -999 -999 -999 -999 ... -999 -999
When I read the file using pandas read_fwf
data = pd.read_fwf('Users/.../file.asc', index_col=False, sep=' ', skiprows=6, header=None, na_values=[-999])
the first three columns are thrown into the 0 column such that I obtain the output
0 1 2 3 4 5 6 7 8 9 ... 641 \
0 -999 -999 -999 -999 NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN
It seems like the function interprets my first 4 columns as an index. index_col=False
didn't help fixing the problem. Also, I tried to let pandas create an index column but couldn't find this feature.
Looking forward to your solution. Thanks.
Upvotes: 1
Views: 5478
Reputation: 210872
UPDATE2: using colspecs
parameter when calling read_fwf()
In [83]: df = pd.read_fwf(fn, skiprows=6, header=None, na_values=[-999],
....: colspecs=[(5,6)] * 654)
In [84]: df.head()
Out[84]:
0 1 2 3 4 5 6 7 8 9 ... 644 645 646 647 648 649 650 651 652 653
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[5 rows x 654 columns]
UPDATE:
use read_csv()
instead of read_fwf()
and it'll work:
In [61]: fn = r'D:\download\BRD_8110_YY_GIS.asc'
In [62]: df = pd.read_csv(fn, skiprows=6, header=None, na_values=[-999], delim_whitespace=True)
In [63]: df.head()
Out[63]:
0 1 2 3 4 5 6 7 8 9 ... 644 645 646 647 648 649 650 651 652 653
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[5 rows x 654 columns]
Upvotes: 3
Reputation: 3335
Use sep='\s+'
as keyword argument as stated in the current documentation for pandas - read_fwf to accept 1 or more white space characters as spearators for fields. I would be reluctant in supplying '\s*'
as this means 0 or more which might get you into trouble ;-)
Upvotes: 0