-
-
Notifications
You must be signed in to change notification settings - Fork 18.2k
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
PDEP-6: Ban upcasting in setitem-like operations #50424
Merged
Merged
Changes from 4 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
1fb0adb
[skip ci] pdep6 draft
5456787
[skip ci] reword
02ff735
[skip ci] compare with DataFrames.jl
e3cc381
[skip ci] note about loss of precision
f6298e9
[skip ci] add examples of operations which would raise
dffef42
[skip ci] note about DataFrame.__setitem__
9fa7675
[skip ci] notes about dataframe case
2ce6ff0
[skip ci] remove special-casing of full slice
4626831
[skip ci] minor fixups
1217a4e
[skip ci] add examples with boolean masks
6798a2d
[skip ci] Merge remote-tracking branch 'upstream/main' into pdep6
a930df1
use more generic indexer in example, clarify the enlargement is out o…
02bab00
dont call workaround "easy"
875cf4c
define indexer
9dcf8d4
clarify
d15a7c1
wip
2c214c7
split up examples, assorted cleanups, clarify scope
1868f3c
mention df.index.intersection
80841d2
make explicit that option 1 was chosen in this pdep
0c4bdff
clarify option 3
MarcoGorelli e6f0c7f
clarify option 2
MarcoGorelli 368ad20
correct "risk annoy" to "risk annoying" so as to not risk annoying re…
MarcoGorelli 35c3f37
Merge remote-tracking branch 'upstream/main' into pdep6
a0ae1fd
add faq
af7e0e4
Merge remote-tracking branch 'upstream/main' into pdep6
a002831
Merge branch 'pdep6' of github.com:MarcoGorelli/pandas into pdep6
3e220f0
add example with 16.000000000000001 to faq
0b02317
minor clarification (when constructing it)
50f0a41
Update web/pandas/pdeps/0006-ban-upcasting.md
MarcoGorelli cc77562
add example of maybe_convert_to_int function
9cee2c7
Merge branch 'pdep6' of github.com:MarcoGorelli/pandas into pdep6
0ff14f1
Merge remote-tracking branch 'upstream/main' into pdep6
8211f37
change status to accepted
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
# PDEP-6: Ban upcasting in setitem-like operations | ||
|
||
- Created: 23 December 2022 | ||
- Status: Draft | ||
- Discussion: [#50402](https://github.com/pandas-dev/pandas/pull/50402) | ||
- Author: [Marco Gorelli](https://github.com/MarcoGorelli) ([original issue](https://github.com/pandas-dev/pandas/issues/39584) by [Joris Van den Bossche](https://github.com/jorisvandenbossche)) | ||
- Revision: 1 | ||
|
||
## Abstract | ||
|
||
The suggestion is that setitem-like operations would | ||
not change a ``Series``' dtype. | ||
|
||
Current behaviour: | ||
```python | ||
In [1]: ser = pd.Series([1, 2, 3], dtype='int64') | ||
|
||
In [2]: ser[2] = 'potage' | ||
|
||
In [3]: ser # dtype changed to 'object'! | ||
Out[3]: | ||
0 1 | ||
1 2 | ||
2 potage | ||
dtype: object | ||
``` | ||
|
||
Suggested behaviour: | ||
|
||
```python | ||
In [1]: ser = pd.Series([1, 2, 3]) | ||
|
||
In [2]: ser[2] = 'potage' # raises! | ||
--------------------------------------------------------------------------- | ||
TypeError: Invalid value 'potage' for dtype int64 | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
## Motivation and Scope | ||
|
||
Currently, pandas is extremely flexible in handling different dtypes. | ||
However, this can potentially hide bugs, break user expectations, and copy data | ||
in what looks like it should be an inplace operation. | ||
|
||
An example of it hiding a bug is: | ||
```python | ||
In [9]: ser = pd.Series(pd.date_range('2000', periods=3)) | ||
|
||
In [10]: ser[2] = '2000-01-04' # works, is converted to datetime64 | ||
|
||
In [11]: ser[2] = '2000-01-04x' # almost certainly a typo - but pandas doesn't error, it upcasts to object | ||
``` | ||
|
||
The scope of this PDEP is limited to setitem-like operations which would operate inplace, such as: | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- ``ser[0] == 2``; | ||
- ``ser.fillna(0, inplace=True)``; | ||
- ``ser.where(ser.isna(), 0, inplace=True)`` | ||
|
||
There may be more. What is explicitly excluded from this PDEP is any operation would have no change | ||
of operating inplace to begin with, such as: | ||
- ``ser.diff()``; | ||
- ``pd.concat([ser, other])``; | ||
- ``ser.mean()``. | ||
|
||
These would keep being allowed to change Series' dtypes. | ||
|
||
## Detailed description | ||
|
||
Concretely, the suggestion is: | ||
- if a ``Series`` is of a given dtype, then a ``setitem``-like operation should not change its dtype; | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- if a ``setitem``-like operation would previously have changed a ``Series``' dtype, it would now raise. | ||
|
||
For a start, this would involve: | ||
|
||
1. changing ``Block.setitem`` such that it doesn't have an ``except`` block in | ||
|
||
```python | ||
value = extract_array(value, extract_numpy=True) | ||
try: | ||
casted = np_can_hold_element(values.dtype, value) | ||
except LossySetitemError: | ||
# current dtype cannot store value, coerce to common dtype | ||
nb = self.coerce_to_target_dtype(value) | ||
return nb.setitem(indexer, value) | ||
else: | ||
``` | ||
|
||
2. making a similar change in ``Block.where``, ``EABlock.setitem``, ``EABlock.where``, and probably more places. | ||
|
||
The above would already require several hundreds of tests to be adjusted. | ||
|
||
### Ban upcasting altogether, or just upcasting to ``object``? | ||
|
||
The trickiest part of this proposal concerns what to do when setting a float in an integer column: | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```python | ||
In [1]: ser = pd.Series([1, 2, 3]) | ||
|
||
In [2]: ser[0] = 1.5 | ||
``` | ||
|
||
This isn't necessarily a sign of a bug, because the user might just be thinking of their ``Series`` as being | ||
numeric (without much regard for ``int`` vs ``float``) - ``'int64'`` is just what pandas happened to infer. | ||
|
||
Possibly options could be: | ||
1. just raise, forcing users to be explicit; | ||
2. convert the float value to ``int`` before setting it; | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
3. limit "banning upcasting" to when the upcasted dtype is ``object``. | ||
phofl marked this conversation as resolved.
Show resolved
Hide resolved
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Let us compare with what other libraries do: | ||
- ``numpy``: option 2 | ||
- ``cudf``: option 2 | ||
- ``polars``: option 2 | ||
- ``R data.frame``: just upcasts (like pandas does now for non-nullable dtypes); | ||
- ``pandas`` (nullable dtypes): option 1 | ||
- ``datatable``: option 1 | ||
- ``DataFrames.jl``: option 1 | ||
|
||
Option ``2`` would be a breaking behaviour change in pandas. Further, | ||
if the objective of this PDEP is to prevent bugs, then this is also not desirable: | ||
someone might set ``1.5`` and later be surprised to learn that they actually set ``1``. | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
There are several downsides to option ``3``: | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- it would be inconsistent with the nullable dtypes' behaviour; | ||
- it would also add complexity to the codebase and to tests; | ||
- it would be hard to teach, as instead of being able to teach a simple rule, | ||
there would be a rule with exceptions; | ||
- there would be a risk of loss of precision; | ||
- it opens the door to other exceptions, such as not upcasting to ``'int16'`` | ||
when trying to set an element of a ``'int8'`` ``Series`` to ``128``. | ||
|
||
Option ``1`` is the maximally safe one in terms of protecting users from bugs, being | ||
consistent with the current behaviour of nullable dtypes, and in being simple to teach. | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## Usage and Impact | ||
|
||
This would make pandas stricter, so there should not be any risk of introducing bugs. If anything, this would help prevent bugs. | ||
|
||
Unfortunately, it would also risk annoy users who might have been intentionally upcasting. | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Given that users can get around this as simply as with a ``.astype({'my_column': float})`` call, | ||
I think it would be more beneficial to the community at large to err on the side of strictness. | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## Timeline | ||
|
||
Deprecate sometime in the 2.x releases (after 2.0.0 has already been released), and enforce in 3.0.0. | ||
|
||
### PDEP History | ||
|
||
- 23 December 2022: Initial draft |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My first reaction was "why only for Series and not DataFrame?", but I think it just applies to DataFrames as well, right? It's just that dtypes are per column (Series), so preserving those is also something that is decided per column.
I would put less stress on that it is only for Series, or here maybe say something like "a Series' or DataFrame column's dtype"