Skip to content
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

BUG: DataFrame.apply returns inconsistent index depending on applied function's return type #35683

Closed
2 tasks done
bubbleyob opened this issue Aug 12, 2020 · 12 comments
Closed
2 tasks done
Labels
Apply Apply, Aggregate, Transform Bug Closing Candidate May be closeable, needs more eyeballs DataFrame DataFrame data structure Regression Functionality that used to work in a prior pandas version

Comments

@bubbleyob
Copy link

  • I have checked that this issue has not already been reported.
  • Possibly related to this issue, but from what I can see, it's not quite the same thing (might be different symptoms of the same problem)
  • I have confirmed this bug exists on the latest version of pandas.

Code Sample

import pandas as pd


def func(col, _type):
    return _type()


df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=['a', 'b'])

for _type in [int, bool, float, str, list, tuple, dict, set]:
    type_lambda = lambda col: func(col, _type)
    print(f'Returning values of type {_type}:', df.apply(type_lambda).index)

With pandas 1.1.0, this outputs:

Returning values of type <class 'int'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'bool'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'float'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'str'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'list'>: RangeIndex(start=0, stop=0, step=1)
Returning values of type <class 'tuple'>: RangeIndex(start=0, stop=0, step=1)
Returning values of type <class 'dict'>: Int64Index([0, 1], dtype='int64')
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    print(f'Returning values of type {_type}:', df.apply(type_lambda).index)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/frame.py", line 7541, in apply
    return op.get_result()
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/apply.py", line 180, in get_result
    return self.apply_standard()
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/apply.py", line 258, in apply_standard
    return self.wrap_results(results, res_index)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/apply.py", line 299, in wrap_results
    return self.wrap_results_for_axis(results, res_index)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/apply.py", line 352, in wrap_results_for_axis
    result = self.obj._constructor(data=results)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/frame.py", line 467, in __init__
    mgr = init_dict(data, index, columns, dtype=dtype)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 283, in init_dict
    return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 83, in arrays_to_mgr
    arrays = _homogenize(arrays, index, dtype)
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 352, in _homogenize
    val, index, dtype=dtype, copy=False, raise_cast_failure=False
  File "/home/louis/venvs/test/lib/python3.7/site-packages/pandas/core/construction.py", line 452, in sanitize_array
    raise TypeError("Set type is unordered")
TypeError: Set type is unordered

Problem description

As shown above, when different data types are turned by the applied function, the index of the result is changed. From what I have seen, this is neither documented behaviour, nor is it consistent with itself. Additionally, in previous versions of pandas, apply worked differently, as shown below.

Expected Output

This is the output when running with pandas 1.0.5 and pandas 1.0.4, and is what I would expect:

Returning values of type <class 'int'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'bool'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'float'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'str'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'list'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'tuple'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'dict'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'set'>: Index(['a', 'b'], dtype='object')

Output of pd.show_versions()

Environment with pandas 1.1.0:

INSTALLED VERSIONS

commit : d9fff27
python : 3.7.5.final.0
python-bits : 64
OS : Linux
OS-release : 5.4.0-42-generic
Version : #46~18.04.1-Ubuntu SMP Fri Jul 10 07:21:24 UTC 2020
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_NZ.UTF-8
LOCALE : en_NZ.UTF-8

pandas : 1.1.0
numpy : 1.19.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.2.1
setuptools : 39.0.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 0.8.0
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pyxlsb : None
s3fs : 0.4.2
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Environment with pandas 1.0.5:

INSTALLED VERSIONS

commit : None
python : 3.7.5.final.0
python-bits : 64
OS : Linux
OS-release : 5.4.0-42-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_NZ.UTF-8
LOCALE : en_NZ.UTF-8

pandas : 1.0.5
numpy : 1.19.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.2.1
setuptools : 39.0.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : None
pyxlsb : None
s3fs : 0.4.2
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None

@bubbleyob bubbleyob added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 12, 2020
@AlexKirko AlexKirko added Apply Apply, Aggregate, Transform DataFrame DataFrame data structure and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 12, 2020
@AlexKirko
Copy link
Member

Hello, @BobbyBlue42 , and thanks for the PR!

Confirmed this behavior for the head of the master branch.
From what I understand, here we force pandas to apply a lambda column-wise, we force that lambda to output an array-like, and then we jam it into an element of the resulting Series, and this leads to Index weirdness.
While the Index inconsistencies are worrying (especially since the behavior was different in 1.0.5), could you perhaps give a more common example (use case) where this bug would surface? It would help us estimate how common running into this is for our users.

@bubbleyob
Copy link
Author

Thanks for checking that for me, @AlexKirko

In my case, this came up when attempting to find date/datetime formats of any string columns in the DataFrame. We're applying a function to find formats (and determine whether there is one format that applies to all values in the column, or different formats for different values). The return value of the applied function is a dictionary containing a status, as well as the format that can be applied to all values in the column. Then, when going through the values in the resulting Series, we attempt to parse the timestamps in df[col] by the format in format_series[col]. Since the return values of the applied function are dictionaries, the Index of the Series is an Int64Index, so we get a KeyError for attempting to access df[0] because the columns of the DataFrame have actual names.

While the timestamp use case might not be particularly common, I think that in general attempting to iterate over the original DataFrame based on the Index of the Series seems quite logical.

@simonjayhawkins
Copy link
Member

From what I have seen, this is neither documented behaviour, nor is it consistent with itself. Additionally, in previous versions of pandas, apply worked differently, as shown below.

I'll mark this as a regression for now pending further investigation/discussion cc @jbrockmendel

the Exception case arises from #34909 (not checked the others)

91802a9 is the first bad commit
commit 91802a9
Author: jbrockmendel jbrockmendel@gmail.com
Date: Thu Jun 25 16:06:10 2020 -0700

PERF: avoid creating many Series in apply_standard (#34909)

@simonjayhawkins simonjayhawkins added this to the 1.1.1 milestone Aug 15, 2020
@simonjayhawkins simonjayhawkins added the Regression Functionality that used to work in a prior pandas version label Aug 15, 2020
@jbrockmendel
Copy link
Member

DataFrame.apply makes a best-guess as to whether it is looking at a reduction or not. A case with an always-empty listlike result is a sharp corner.

DataFrame.apply has a result_type keyword that does/should govern the behavior in ambiguous cases like this. I think df.apply(lambda x: [], result_type="reduce") should give you the behavior you want, but it looks like it isn't transferring the columns to the index correctly.

@simonjayhawkins
Copy link
Member

heads up: associated PR moved off 1.1.1

@simonjayhawkins simonjayhawkins modified the milestones: 1.1.1, 1.1.2 Aug 20, 2020
@rhshadrach
Copy link
Member

Using result_type="reduce" as @jbrockmendel mentioned, I now see the expected output on master:

Returning values of type <class 'int'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'bool'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'float'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'str'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'list'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'tuple'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'dict'>: Index(['a', 'b'], dtype='object')
Returning values of type <class 'set'>: Index(['a', 'b'], dtype='object')

Also, PR #35777 mentions this issue in the whatsnew; can this issue be closed?

@simonjayhawkins simonjayhawkins modified the milestones: 1.1.2, 1.1.3 Sep 7, 2020
@simonjayhawkins
Copy link
Member

Also, PR #35777 mentions this issue in the whatsnew; can this issue be closed?

moved off 1.1.2 milestone (scheduled for this week) as no PRs to fix in the pipeline and pending further discussion

@simonjayhawkins simonjayhawkins modified the milestones: 1.1.3, 1.1.4 Oct 5, 2020
@simonjayhawkins
Copy link
Member

moved off 1.1.3 milestone (overdue) pending further discussion

@rhshadrach
Copy link
Member

@jbrockmendel I think your PR linked above closes out this issue, is that correct?

@jbrockmendel
Copy link
Member

#35777 fixed the definitely-wrong behavior where the result_type keyword was not respected, doesn't change the not-clearly-wrong behavior in the OP (which Im ok with calling not-a-bug)

@simonjayhawkins simonjayhawkins added the Closing Candidate May be closeable, needs more eyeballs label Oct 29, 2020
@simonjayhawkins simonjayhawkins modified the milestones: 1.1.4, 1.1.5 Oct 29, 2020
@simonjayhawkins
Copy link
Member

moved off 1.1.4 milestone (scheduled for release tomorrow) as no PRs to fix in the pipeline

@rhshadrach
Copy link
Member

+1 on closing. The edge case has two valid interpretations, which ever we default to will be confusing to someone. The argument result_type can be used avoid undesired behavior. I don't see anything more that can be done here.

@jreback jreback removed this from the 1.1.5 milestone Nov 25, 2020
@jreback jreback added this to the Contributions Welcome milestone Nov 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Apply Apply, Aggregate, Transform Bug Closing Candidate May be closeable, needs more eyeballs DataFrame DataFrame data structure Regression Functionality that used to work in a prior pandas version
Projects
None yet
Development

No branches or pull requests

6 participants