Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions doc/source/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1268,11 +1268,22 @@ is whitespace).
df = pd.read_fwf('bar.csv', header=None, index_col=0)
df

.. versionadded:: 0.20.0

``read_fwf`` supports the ``dtype`` parameter for specifying the types of
parsed columns to be different from the inferred type.

.. ipython:: python

pd.read_fwf('bar.csv', header=None, index_col=0).dtypes
pd.read_fwf('bar.csv', header=None, dtype={2: 'object'}).dtypes

.. ipython:: python
:suppress:

os.remove('bar.csv')


Indexes
'''''''

Expand Down
9 changes: 9 additions & 0 deletions doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ The ``dtype`` keyword argument in the :func:`read_csv` function for specifying t
pd.read_csv(StringIO(data), engine='python').dtypes
pd.read_csv(StringIO(data), engine='python', dtype={'a':'float64', 'b':'object'}).dtypes

The ``dtype`` keyword argument is also now supported in the :func:`read_fwf` function for parsing
fixed-width text files.

.. ipython:: python

data = "a b\n1 2\n3 4"
pd.read_fwf(StringIO(data)).dtypes
pd.read_fwf(StringIO(data), dtype={'a':'float64', 'b':'object'}).dtypes

.. _whatsnew_0200.enhancements.other:

Other enhancements
Expand Down
20 changes: 20 additions & 0 deletions pandas/io/tests/parser/test_read_fwf.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,23 @@ def test_variable_width_unicode(self):
header=None, encoding='utf8')
tm.assert_frame_equal(expected, read_fwf(
BytesIO(test.encode('utf8')), header=None, encoding='utf8'))

def test_dtype(self):
data = ''' a b c
1 2 3.2
3 4 5.2
'''
colspecs = [(0, 5), (5, 10), (10, None)]
result = pd.read_fwf(StringIO(data), colspecs=colspecs)
expected = pd.DataFrame({
'a': [1, 3],
'b': [2, 4],
'c': [3.2, 5.2]}, columns=['a', 'b', 'c'])
tm.assert_frame_equal(result, expected)

expected['a'] = expected['a'].astype('float64')
expected['b'] = expected['b'].astype(str)
expected['c'] = expected['c'].astype('int32')
result = pd.read_fwf(StringIO(data), colspecs=colspecs,
dtype={'a': 'float64', 'b': str, 'c': 'int32'})
tm.assert_frame_equal(result, expected)