Skip to content

BUG: Pandas squashes 1-dimensional Numpy array with shape (1,) down to a 0-dimensional array #59249

@sunghjung3

Description

@sunghjung3

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 pandas as pd
import numpy as np

df = pd.DataFrame(columns=['x'])
arr0 = np.array([1., 2.])
df.loc[0, "x"] = arr0
print(df.loc[0, "x"].shape)  # prints (2,)
arr1 = np.array([1.])
df.loc[1, "x"] = arr1
print(df.loc[1, "x"].shape)  # prints (). Should print (1,)

Issue Description

When a 1-dimensional Numpy array that only has 1 entry is stored to a DataFrame, Pandas seems to automatically make it a 0-dimensional array.

This is extremely inconvenient when the entries of both df.loc[0, "x"] and df.loc[1, "x"] are accessed later like df.loc[1, "x"][i] just for it to cause Numpy to raise an IndexError because df.loc[1, "x"] is now a 0-dimensional array, not a 1-dimensional array.

NOTE: This was not an issue in Pandas 2.0.0, but it is in version 2.2.2. I am not sure exactly which version in between this was introduced.

FYI: If a higher dimensional array with 1 entry is stored (e.g. np.array([[1.]])), then the shape is correctly preserved. It is only an issue when the array is 1-dimensional.

Expected Behavior

print(df.loc[1, "x"].shape) should print (1,).

Installed Versions

INSTALLED VERSIONS

commit : d9cdd2e
python : 3.11.9.final.0
python-bits : 64
OS : Linux
OS-release : 4.18.0-477.15.1.el8_8.x86_64
Version : #1 SMP Wed Jun 28 15:04:18 UTC 2023
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.2.2
numpy : 1.26.4
pytz : 2024.1
dateutil : 2.9.0
setuptools : 70.3.0
pip : 24.0
Cython : None
pytest : 8.2.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.4
IPython : 8.26.0
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : 2024.6.1
gcsfs : None
matplotlib : 3.9.1
numba : 0.60.0
numexpr : 2.10.0
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.14.0
sqlalchemy : None
tables : 3.9.2
tabulate : None
xarray : None
xlrd : None
zstandard : 0.22.0
tzdata : 2024.1
qtpy : None
pyqt5 : None

Metadata

Metadata

Labels

BugIndexingRelated to indexing on series/frames, not to indexes themselvesNeeds DiscussionRequires discussion from core team before further action

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions