Description
Pandas version checks
I have checked that this issue has not already been reported.
I have confirmed this bug exists on the latest version of pandas.
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import numpy as np
import pandas as pd
print('# array')
a = np.array([False, True])
print(a.dtype)
df = pd.DataFrame.from_dict({'a': a})
print(df['a'].dtype)
print('# masked array')
a_ = np.ma.array([False, True], mask=[1, 0])
print(a_.dtype)
df_ = pd.DataFrame.from_dict({'a': a_})
print(df_['a'].dtype)
Issue Description
For a regular numpy array
the bool
type is preserved, but for a maskedarray
it becomes object
:
# array
bool
bool
# masked array
bool
object
Expected Behavior
The last line should be boolean
.
Installed Versions
/opt/python/3.11.6/lib/python3.11/site-packages/_distutils_hack/init.py:33: UserWarning: Setuptools is replacing distutils.
warnings.warn("Setuptools is replacing distutils.")
INSTALLED VERSIONS
commit : 7368686
python : 3.11.6.final.0
python-bits : 64
OS : Linux
OS-release : 6.2.0-1018-azure
Version : #18~22.04.1-Ubuntu SMP Tue Nov 21 19:25:02 UTC 2023
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : en_US.UTF-8
pandas : 3.0.0.dev0+170.g7368686710
numpy : 1.26.1
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 68.2.2
pip : 23.3.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 : 3.1.2
IPython : None
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : 2023.2.0
fsspec : 2023.10.0
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 14.0.1
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.10.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None
Activity
[-]BUG: DataFrame.from_dict loses type with NumPy MaskedArray[/-][+]BUG: DataFrame.from_dict loses bool type with NumPy MaskedArray[/+]DarthKitten2130 commentedon Jan 28, 2024
Uhh, so this actually has nothing to do with masked arrays as I discovered, it has to do with the fact that for some reason pandas parses a bool column with NaN values as an object dtype, which I posted about in #57119 .
DarthKitten2130 commentedon Jan 28, 2024
@mroeschke isn't this also expected behaviour then?