Skip to content

ENH/TST/DOC: set infer_nrows for read_fwf (GH15138) #23238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Nov 26, 2018

Conversation

rdmontgomery
Copy link
Contributor

@rdmontgomery rdmontgomery commented Oct 19, 2018

read_fwf can infer the widths of columns of a dataset from a file or buffer, but if the widths change after the first 100 rows, then the default behavior fails to capture the data correctly. This PR addresses that issue by allowing the user to set a parameter infer_nrows that is passed down to the appropriate function.

The associated test ensures that colspecs can be determined from the first row, thereby missing data from the subsequent rows and verifying the expected behavior.

rdmontgomery added 4 commits October 19, 2018 09:49
Previously, read_fwf would infer the width of the columns from the first
100 rows of data. It now accepts a parameter infer_nrows that lets the
user choose how many rows to use in the inference.
Fixed reference in colspecs. Switched half-open interval
representation from non-standard [from, to[ to standard [from, to).
@pep8speaks
Copy link

Hello @rdmontgomery! Thanks for submitting the PR.

@WillAyd WillAyd added the IO Data IO issues that don't fit into a more specific label label Oct 23, 2018
@@ -716,7 +720,8 @@ def parser_f(filepath_or_buffer,


@Appender(_read_fwf_doc)
def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, **kwds):
def read_fwf(filepath_or_buffer, colspecs='infer', infer_nrows=100,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should add the new keyword to the end of positional arguments so as not to interfere with existing user code

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @WillAyd.

@@ -3420,11 +3428,11 @@ def get_rows(self, n, skiprows=None):
self.buffer = iter(buffer_rows)
return detect_rows

def detect_colspecs(self, n=100, skiprows=None):
def detect_colspecs(self, infer_nrows, skiprows=None):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why you changed this from required to optional? Think that might be causing your test failures

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was an oversight. Fixed now. Thanks!

@codecov
Copy link

codecov bot commented Oct 23, 2018

Codecov Report

Merging #23238 into master will increase coverage by <.01%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master   #23238      +/-   ##
==========================================
+ Coverage   92.29%   92.29%   +<.01%     
==========================================
  Files         161      161              
  Lines       51498    51500       +2     
==========================================
+ Hits        47530    47533       +3     
+ Misses       3968     3967       -1
Flag Coverage Δ
#multiple 90.69% <100%> (ø) ⬆️
#single 42.42% <44.44%> (-0.01%) ⬇️
Impacted Files Coverage Δ
pandas/io/parsers.py 95.36% <100%> (+0.06%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update a7b187a...ecf35d6. Read the comment docs.

@rdmontgomery
Copy link
Contributor Author

Hi @WillAyd, thanks for reviewing my code. I made the requested changes and it looks like everything passed now. Is there anything else I can do for this?

@@ -3361,13 +3367,15 @@ class FixedWidthReader(BaseIterator):
A reader of fixed-width lines.
"""

def __init__(self, f, colspecs, delimiter, comment, skiprows=None):
def __init__(self, f, colspecs, delimiter, comment, infer_nrows=100,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still need to change position of infer_nrows to be at the end here

@@ -3420,11 +3428,11 @@ def get_rows(self, n, skiprows=None):
self.buffer = iter(buffer_rows)
return detect_rows

def detect_colspecs(self, n=100, skiprows=None):
def detect_colspecs(self, infer_nrows=100, skiprows=None):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I actually see another problem here. I co-opted n because it was performing the intended function of infer_nrows, but that would also break previous code that relied on calling n explicitly. I'll return the code and tack on infer_nrows at the end, like you pointed out.

Rework so that if infer_nrows is not set, detect_colspecs still uses
n=100, preserving previous behavior. If infer_nrows comes down the pipe,
the default n is overwritten. Also make sure that the new parameter
infer_nrows is the trailing keyword in all function calls.

Fix the documentation to reflect these changes.
Copy link
Contributor

@jreback jreback left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pls add a whatsnew note as well (other enhancements)

A list of field widths which can be used instead of 'colspecs' if
the data which are not being skipped via skiprows (default='infer'),
or by using the `infer_nrows` parameter.
infer_nrows : int, default None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add infer_nrows after widths. pls add a versionadded tag

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default 100

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm switching the places and adding a versionadded tag.

Regarding the default of None, I mention my reasoning in the comment for read_fwf. I do state here in the docs
If not set (or set to `None`), default behavior of 100 rows is used.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right but better to simply say its 100

@@ -716,7 +722,8 @@ def parser_f(filepath_or_buffer,


@Appender(_read_fwf_doc)
def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, **kwds):
def read_fwf(filepath_or_buffer, colspecs='infer', widths=None,
infer_nrows=None, **kwds):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this be 100?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might be bending over to maintain backwards compatibility here (or I might be wrong), but I decided to let infer_nrows default to None so that if there is old code that had explicitly called detect_colspecs(n=1234), the function would behave as they expected. If someone sets infer_nrows to a number, then n is overwritten with infer_nrows.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To clarify a little further, this was the only way I could think to respect old code that explicitly set n in a direct call to detect_colspecs. Any new code that chooses to use infer_nrows will overwrite n, but I did not want to automatically overwrite n with a default of 100 if someone had already chosen to do otherwise.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is still backward compat. If n is not None, use it, else use infer_nrows. (and let's deprecate setting n that way anyhow).

@jreback jreback added the IO CSV read_csv, to_csv label Oct 26, 2018
the intervals are contiguous.
infer_nrows : int, default None
The number of rows to consider when letting the parser determine the
``colspecs``. If not set (or set to `None`), default behavior of 100
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put literals like None in double backpacks

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you point me to a guide on the use of single and double backticks in pandas or GitHub? I haven't been able to find anything definitive. Or is it just single backticks for code and double backticks for literals? Should colspecs here be in singles?

@@ -3422,10 +3435,12 @@ def get_rows(self, n, skiprows=None):
self.buffer = iter(buffer_rows)
return detect_rows

def detect_colspecs(self, n=100, skiprows=None):
def detect_colspecs(self, n=100, skiprows=None, infer_nrows=None):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is anything actually calling this with n? I believe this is an internal method so maybe here we can get by with just eliminating n altogether and replacing it with the value from infer_nrows

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's what I had proposed initially and had replaced n with infer_nrows in place. Your comment about putting the new keyword as a trailing argument is what made me realize that it was possible for someone's code to have instantiated FixedWidthReader and explicitly set n.

Granted, that seems like a rare use case, but I was able to implement a solution that handled both cases. However, this solution seems to have come at the cost of confusing documentation, where infer_nrows has a default of None in order for read_fwf(colspecs='infer') to default to inferring from the first 100 rows, as was the case beforehand.

If you and @jreback prefer, I'm happy to use either
detect_colspecs(self, infer_nrows=100, skiprows=None) or
detect_colspecs(self, skiprows=None, infer_nrows=100)
with the awareness that it might be a breaking change in rare cases.

A list of field widths which can be used instead of 'colspecs' if
the data which are not being skipped via skiprows (default='infer'),
or by using the `infer_nrows` parameter.
infer_nrows : int, default None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right but better to simply say its 100

@@ -716,7 +722,8 @@ def parser_f(filepath_or_buffer,


@Appender(_read_fwf_doc)
def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, **kwds):
def read_fwf(filepath_or_buffer, colspecs='infer', widths=None,
infer_nrows=None, **kwds):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is still backward compat. If n is not None, use it, else use infer_nrows. (and let's deprecate setting n that way anyhow).

rdmontgomery added 2 commits October 28, 2018 15:01
Preserve backwards compatibility by allowing n to be set, but the new
default will be to use infer_nrows.
@rdmontgomery
Copy link
Contributor Author

Thanks, guys. I appreciate your help in moving this forward.

I'm not sure what happened with the CircleCI build this time around. Looks like maybe debian.org was having temporary troubles. Any advice here?

Err:3 http://deb.debian.org/debian stretch Release
404 Not Found

@rdmontgomery
Copy link
Contributor Author

Hi @jreback and @WillAyd, can you help me understand why the CircleCI test failed? I'd like to re-run the test without pushing any code changes, but I haven't been able to figure out how.

@jreback
Copy link
Contributor

jreback commented Nov 6, 2018

looks suprious. merge master and push again.

# Regex escape the delimiters
delimiters = ''.join(r'\%s' % x for x in self.delimiter)
pattern = re.compile('([^%s]+)' % delimiters)
rows = self.get_rows(n, skiprows)
if n:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is an internal method only and not part of the api I wonder if it wouldn't be better to just replace the n keyword with infer_rows

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds reasonable to me, @WillAyd. Would it be better to leave the keyword order as-is with n removed or should I reorder like this def detect_colspecs(self, infer_nrows=100, skiprows=None):? Or does that really not matter at all?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd go with the latter unless @jreback has a differing opinion

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think ok to reorder that is an internal method

@jreback jreback added this to the 0.24.0 milestone Nov 11, 2018
@jreback
Copy link
Contributor

jreback commented Nov 11, 2018

@rdmontgomery can you merge master. @WillAyd if you have any comments.

@WillAyd
Copy link
Member

WillAyd commented Nov 12, 2018

@rdmontgomery would be curious if you have thoughts on my previous comment. Always good to simplify / cleanup internal code if possible

@jreback
Copy link
Contributor

jreback commented Nov 18, 2018

pls merge master as well

@jreback
Copy link
Contributor

jreback commented Nov 18, 2018

rebased.

@WillAyd
Copy link
Member

WillAyd commented Nov 24, 2018

@rdmontgomery can you address last comment around the re-ordering of the internal function signature? Once that is done I'm OK to approve and merge

@rdmontgomery
Copy link
Contributor Author

@rdmontgomery can you address last comment around the re-ordering of the internal function signature? Once that is done I'm OK to approve and merge

I'll jump on it tomorrow morning! I've been in the last negotiations of a job offer and I just wrapped that up today. I've got some time again!

rdmontgomery added 3 commits November 25, 2018 14:38
Let infer_nrows replace the internal parameter n and reorder the
keywords.
Fix bug introduced when master was merged back in and the function
definition was changed along with the docstring.
@WillAyd WillAyd merged commit 1f02bf2 into pandas-dev:master Nov 26, 2018
@WillAyd
Copy link
Member

WillAyd commented Nov 26, 2018

Thanks @rdmontgomery !

Good luck with the job

Pingviinituutti pushed a commit to Pingviinituutti/pandas that referenced this pull request Feb 28, 2019
Pingviinituutti pushed a commit to Pingviinituutti/pandas that referenced this pull request Feb 28, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
IO CSV read_csv, to_csv IO Data IO issues that don't fit into a more specific label
Projects
None yet
Development

Successfully merging this pull request may close these issues.

read_fwf 'infer' where first hundred lines differ from other lines
4 participants