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: Creating a DataFrame from a structured masked NumPy array. #42739

Open
2 of 3 tasks
demitri opened this issue Jul 26, 2021 · 3 comments
Open
2 of 3 tasks

BUG: Creating a DataFrame from a structured masked NumPy array. #42739

demitri opened this issue Jul 26, 2021 · 3 comments
Labels
Constructors Series/DataFrame/Index/pd.array Constructors Docs

Comments

@demitri
Copy link

demitri commented Jul 26, 2021

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import numpy as np
import pandas as pd
import numpy.ma as ma

# create a masked, structured array
a = np.ma.array([(1, 2.2), (42, 5.5)],
                dtype=[('a',int),('b',float)],
                mask=[(True,False),(False,True)])

b = pd.DataFrame(a)

Problem description

This is somewhere between a bug report and a feature request? The above code returns this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-a4c5236a3cd4> in <module>
----> 1 pd.DataFrame(a)

/usr/local/anaconda/lib/python3.8/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    636             # a masked array
    637             else:
--> 638                 data = sanitize_masked_array(data)
    639                 mgr = ndarray_to_mgr(
    640                     data,

/usr/local/anaconda/lib/python3.8/site-packages/pandas/core/construction.py in sanitize_masked_array(data)
    452     """
    453     mask = ma.getmaskarray(data)
--> 454     if mask.any():
    455         data, fill_value = maybe_upcast(data, copy=True)
    456         data.soften_mask()  # set hardmask False if it was True

/usr/local/anaconda/lib/python3.8/site-packages/numpy/core/_methods.py in _any(a, axis, dtype, out, keepdims, where)
     54     # Parsing keyword arguments is currently fairly slow, so avoid it for now
     55     if where is True:
---> 56         return umr_any(a, axis, dtype, out, keepdims)
     57     return umr_any(a, axis, dtype, out, keepdims, where=where)
     58 

TypeError: cannot perform reduce with flexible type

The documentation notes that:

Alternatively, you may pass a numpy.MaskedArray as the data argument to the DataFrame constructor, and its masked entries will be considered missing.

The above works if dtype is omitted; all values are "upgraded" to floats.

Expected Output

Several possibilities:

  • This is expected behavior. If so, it would be nice to have the documentation linked above note that masked structured NumPy arrays are not supported. The code should also raise the appropriate exception informing the user these arrays are not supported (e.g. ValueError?).
  • This functionality is supported. If so, this appears to be a bug.
  • Functionality is supported, but with extra steps. It seems as though this conversion is possible with these steps.
    • Use numpy.ma.MaskedArray.filled and fill the NumPy masked array with "special" (e.g. 1e20, 99999) values based on data type.
    • Convert the array to a DataFrame.
    • Convert any integer series to the nullable int type Int64.
    • Replace the same filled values to appropriate NULL values, e.g. NaN, pd.NA.

Options to address the latter case can be either supported in code or else documentation.

This issue was discussed on StackOverflow here (my question).

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f00ed8f
python : 3.8.8.final.0
python-bits : 64
OS : Darwin
OS-release : 20.6.0
Version : Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.0
numpy : 1.20.3
pytz : 2021.1
dateutil : 2.8.2
pip : 21.1.3
setuptools : 52.0.0.post20210125
Cython : 0.29.24
pytest : 6.2.4
hypothesis : None
sphinx : 4.0.2
blosc : None
feather : None
xlsxwriter : 1.4.4
lxml.etree : 4.6.3
html5lib : 1.1
pymysql : None
psycopg2 : 2.8.6 (dt dec pq3 ext lo64)
jinja2 : 3.0.1
IPython : 7.22.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : 1.3.2
fsspec : 2021.07.0
fastparquet : None
gcsfs : None
matplotlib : 3.3.4
numexpr : 2.7.3
odfpy : None
openpyxl : 3.0.7
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.6.2
sqlalchemy : 1.4.21
tables : 3.6.1
tabulate : None
xarray : 0.18.2
xlrd : 2.0.1
xlwt : 1.3.0
numba : 0.53.0

@demitri demitri added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jul 26, 2021
@jbrockmendel
Copy link
Member

we recently deprecated support for MaskedRecords, which I think is similar to structured+masked, right?

@jreback
Copy link
Contributor

jreback commented Jul 26, 2021

yeah not sure we really need to support these types as very uncommon

@demitri
Copy link
Author

demitri commented Jul 26, 2021

OK, good to know. Shame though since there is a clear path between the two, although the same could be said from a DataFrame with "null" values to a structured masked NumPy array. Then perhaps a small note in the reference documentation to say this would be great.

@mroeschke mroeschke added Constructors Series/DataFrame/Index/pd.array Constructors Docs and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Constructors Series/DataFrame/Index/pd.array Constructors Docs
Projects
None yet
Development

No branches or pull requests

4 participants