8000 ENH: Allow compression in NDFrame.to_csv to be a dict with optional arguments (#26023) by drew-heenan · Pull Request #26024 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

ENH: Allow compression in NDFrame.to_csv to be a dict with optional arguments (#26023) #26024

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 41 commits into from
Aug 26, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
4e73dc4
ENH/BUG: Add arcname to to_csv for ZIP compressed csv filename (#26023)
drew-heenan Apr 8, 2019
ab7620d
DOC: Updated docs for arcname in NDFrame.to_csv (#26023)
drew-heenan Apr 8, 2019
2e782f9
conform to line length limit
drew-heenan Apr 8, 2019
83e8834
Fixed test_to_csv_zip_arcname for Windows paths
drew-heenan Apr 8, 2019
d238878
Merge remote-tracking branch 'upstream/master' into issue-26023
drew-heenan Apr 8, 2019
b41be54
to_csv compression may now be dict with possible keys 'method' and 'a…
drew-heenan Apr 9, 2019
60ea58c
test_to_csv_compression_dict uses compression_only fixture
drew-heenan Apr 9, 2019
8ba9082
delegate dict handling to _get_compression_method, type annotations
drew-heenan Apr 10, 2019
0a3a9fd
fix import order, None type annotations
drew-heenan Apr 10, 2019
a1cb3f7
compression args passed as kwargs, update relevant docs
drew-heenan Apr 14, 2019
af2a96c
style/doc improvements, change arcname to archive_name
drew-heenan Apr 15, 2019
5853a28
Merge branch 'master' into issue-26023
drew-heenan Apr 15, 2019
789751f
Merge branch 'master' into issue-26023
drew-heenan Apr 22, 2019
5b09e6f
add to_csv example, no method test, Optional types, tweaks; update wh…
drew-heenan Apr 22, 2019
68a2b4d
remove Index import type ignore
drew-heenan Apr 22, 2019
c856f50
Revert "remove Index import type ignore"
drew-heenan Apr 22, 2019
8df6c81
Merge remote-tracking branch 'upstream/master' into issue-26023
drew-heenan Apr 23, 2019
40d0252
Merge branch 'master' into issue-26023
drew-heenan Apr 26, 2019
18a735d
Improve docs/examples
drew-heenan May 5, 2019
103c877
Merge branch 'master' into issue-26023
drew-heenan May 5, 2019
b6c34bc
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Jun 8, 2019
969d387
Added back missed Callable import in generic
WillAyd Jun 8, 2019
abfbc0f
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Jun 9, 2019
04ae25d
Address comments
WillAyd Jun 9, 2019
9c22652
Typing cleanup
WillAyd Jun 9, 2019
56a75c2
Cleaned up docstring
WillAyd Jun 9, 2019
bbfea34
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Jun 23, 2019
7717f16
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Jul 15, 2019
779511e
blackify
WillAyd Jul 15, 2019
780eb04
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Jul 16, 2019
6c4e679
Added annotations where feasible
WillAyd Jul 16, 2019
1b567c9
Black and lint
WillAyd Jul 16, 2019
9324b63
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Jul 17, 2019
7cf65ee
isort fixup
WillAyd Jul 17, 2019
29374f3
Docstring fixup and more annotations
WillAyd Jul 17, 2019
6701aa4
Merge remote-tracking branch 'upstream/master' into issue-26023
WillAyd Aug 24, 2019
0f5489d
lint fixup
WillAyd Aug 24, 2019
e04138e
mypy fixup
WillAyd Aug 24, 2019
6f2bf00
whatsnew fixup
WillAyd Aug 25, 2019
865aa81
Annotation and doc fixups
WillAyd Aug 25, 2019
8d1deee
mypy typeshed bug fix
WillAyd Aug 25, 2019
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
Prev Previous commit
Next Next commit
compression args passed as kwargs, update relevant docs
  • Loading branch information
drew-heenan committed Apr 14, 2019
commit a1cb3f7917efedc52d5d98c4e162a66c9db8a06b
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Other Enhancements
- :class:`RangeIndex` has gained :attr:`~RangeIndex.start`, :attr:`~RangeIndex.stop`, and :attr:`~RangeIndex.step` attributes (:issue:`25710`)
- :class:`datetime.timezone` objects are now supported as arguments to timezone methods and constructors (:issue:`25065`)
- :meth:`DataFrame.query` and :meth:`DataFrame.eval` now supports quoting column names with backticks to refer to names with spaces (:issue:`6508`)
- :meth:`NDFrame.to_csv` now supports dicts as ``compression`` argument with key ``'method'`` being the compression method and optional key 8000 ``'arcname'`` specifying the archived CSV file name when the compression method is ``'zip'``. If key ``'arcname'`` unspecified or ``compression='zip'``, maintains previous behavior. (:issue:`26023`)
- :meth:`NDFrame.to_csv` now supports dicts as ``compression`` argument with key ``'method'`` being the compression method and others as kwargs of ``ByteZipFile`` when the compression method is ``'zip'``. (:issue:`26023`)
Copy link
Contributor

Choose a reason for hiding this comment

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

says Series.to_csv and DataFrame.to_csv

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jreback To clarify, do you mean that it should say Series.to_csv and DataFrame.to_csv instead of just NDFrame.to_csv?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, that's what @jreback is trying to say

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Got it - I've changed the doc to list both.


.. _whatsnew_0250.api_breaking:

Expand Down
3 changes: 2 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2984,7 +2984,8 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
.. versionchanged:: 0.25.0

May now be a dict with key 'method' as compression mode
and 'arcname' as CSV file name if mode is 'zip'
and other entries as ByteZipFile kwargs if compression mode
is 'zip'

quoting : optional constant from csv module
Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
Expand Down
37 changes: 11 additions & 26 deletions pandas/io/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import lzma
import mmap
import os
from typing import Dict, Union
from typing import Dict, Tuple, Union
from urllib.error import URLError # noqa
from urllib.parse import ( # noqa
urlencode, urljoin, urlparse as parse_url, uses_netloc, uses_params,
Expand Down Expand Up @@ -269,40 +269,27 @@ def _get_compression_method(compression: Union[str, Dict, None]):

def _infer_compression(filepath_or_buffer, compression):
"""
Get the compression method for filepath_or_buffer. If compression mode is
'infer', the inferred compression method is returned. Otherwise, the input
Get the compression method for filepath_or_buffer. If compression='infer',
the inferred compression method is returned. Otherwise, the input
compression method is returned unchanged, unless it's invalid, in which
case an error is raised.

Parameters
----------
filepath_or_buffer :
a path (str) or buffer
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None} or dict
If string, specifies compression mode. If dict, value at key 'method'
specifies compression mode. If compression mode is 'infer' and
`filepath_or_buffer` is path-like, then detect compression from the
following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no
compression).

.. versionchanged 0.25.0

May now be a dict with required key 'method' specifying compression
mode

compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}
If 'infer' and `filepath_or_buffer` is path-like, then detect
compression from the following extensions: '.gz', '.bz2', '.zip',
or '.xz' (otherwise no compression).
Returns
-------
string or None :
compression method

Raises
------
ValueError on invalid compression specified
"""

# Handle compression as dict
compression, _ = _get_compression_method(compression)

# No compression has been explicitly specified
if compression is None:
return None
Expand Down Expand Up @@ -357,7 +344,8 @@ def _get_handle(path_or_buf, mode, encoding=None,
.. versionchanged:: 0.25.0

May now be a dict with key 'method' as compression mode
and 'arcname' as CSV file name if mode is 'zip'
and other keys as kwargs for ByteZipFile if compression
mode is 'zip'.

memory_map : boolean, default False
See parsers._parser_params for more information.
Expand All @@ -374,7 +362,7 @@ def _get_handle(path_or_buf, mode, encoding=None,
"""
try:
from s3fs import S3File
need_text_wrapping = (BytesIO, S3File)
need_text_wrapping = (BytesIO, S3File) # type: Tuple
Copy link
Member

Choose a reason for hiding this comment

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

Was this throwing a Typing error? Think MyPy should be able to infer here

Copy link
Contributor Author
@drew-heenan drew-heenan Apr 15, 2019

Choose a reason for hiding this comment

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

@WillAyd Yeah, it was. Couldn’t tell why, but MyPy couldn’t infer when I added types to the function definition. It also occurred on from pandas import Index in csvs.py

Copy link
Member

Choose a reason for hiding this comment

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

What error was it giving you?

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 giving pandas/io/common.py:367: error: Incompatible types in assignment (expression has type "Tuple[Type[BytesIO]]", variable has type "Tuple[Type[BytesIO], Any]") only if any of the function's arguments have type annotations.

except ImportError:
need_text_wrapping = (BytesIO,)

Expand Down Expand Up @@ -407,10 +395,7 @@ def _get_handle(path_or_buf, mode, encoding=None,

# ZIP Compression
elif compression == 'zip':
arcname = None
if 'arcname' in compression_args:
arcname = compression_args['arcname']
zf = BytesZipFile(path_or_buf, mode, arcname=arcname)
zf = BytesZipFile(path_or_buf, mode, **compression_args)
# Ensure the container is closed as well.
handles.append(zf)
if zf.mode == 'w':
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/csvs.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def __init__(self, obj, path_or_buf=None, sep=",", na_rep='',
self.data_index = obj.index
if (isinstance(self.data_index, (ABCDatetimeIndex, ABCPeriodIndex)) and
date_format is not None):
from pandas import Index
from pandas import Index # type: ignore
Copy link
Member

Choose a reason for hiding this comment

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

What error was this giving you?

Copy link
Contributor Author
@drew-heenan drew-heenan Apr 17, 2019

Choose a reason for hiding this comment

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

MyPy was giving pandas/io/formats/csvs.py:125: error: Module 'pandas' has no attribute 'Index'; It appears to only occur if there are type annotations on any CSVFormatter parameters.

Copy link
Member

Choose a reason for hiding this comment

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

Make sure you try again on master - I think a separate PR should have resolved this already

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The same error appears on master if any type annotations are added.

Copy link
Member

Choose a reason for hiding this comment

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

@drew-heenan can you remove this and push as a new commit? Again thought we resolved this in a separate PR so would like to validate its not a mypy versioning thing between your local environment and what we have on CI

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@WillAyd Just did that - the error still appears.

Copy link
Member

Choose a reason for hiding this comment

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

Hmm OK thanks for confirming. @ryankarlos not sure if you have any insight - thought this would be resolved by #26019

@drew-heenan this isn't a blocker so OK to add back in the ignore I think; can review separate from this

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@WillAyd Got it, thanks for checking!

self.data_index = Index([x.strftime(date_format) if notna(x) else
'' for x in self.data_index])

Expand Down
0