Skip to content

Commit e0c5767

Browse files
Backport PR #42735: REGR: DataFrame.from_records with empty records #42456 (#42740)
Co-authored-by: jbrockmendel <[email protected]>
1 parent 3f32083 commit e0c5767

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

doc/source/whatsnew/v1.3.2.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Performance regression in :meth:`DataFrame.isin` and :meth:`Series.isin` for nullable data types (:issue:`42714`)
1818
- Regression in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`)
19-
-
19+
- Regression in :meth:`DataFrame.from_records` with empty records (:issue:`42456`)
2020
-
2121

2222
.. ---------------------------------------------------------------------------

pandas/core/internals/construction.py

+8
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,14 @@ def to_arrays(
761761
# i.e. numpy structured array
762762
columns = ensure_index(data.dtype.names)
763763
arrays = [data[name] for name in columns]
764+
765+
if len(data) == 0:
766+
# GH#42456 the indexing above results in list of 2D ndarrays
767+
# TODO: is that an issue with numpy?
768+
for i, arr in enumerate(arrays):
769+
if arr.ndim == 2:
770+
arrays[i] = arr[:, 0]
771+
764772
return arrays, columns
765773
return [], ensure_index([])
766774

pandas/tests/frame/constructors/test_from_records.py

+13
Original file line numberDiff line numberDiff line change
@@ -457,3 +457,16 @@ def test_from_records_empty_with_nonempty_fields_gh3682(self):
457457
b = a[:0]
458458
df2 = DataFrame.from_records(b, index="id")
459459
tm.assert_frame_equal(df2, df.iloc[:0])
460+
461+
def test_from_records_empty2(self):
462+
# GH#42456
463+
dtype = [("prop", int)]
464+
shape = (0, len(dtype))
465+
arr = np.empty(shape, dtype=dtype)
466+
467+
result = DataFrame.from_records(arr)
468+
expected = DataFrame({"prop": np.array([], dtype=int)})
469+
tm.assert_frame_equal(result, expected)
470+
471+
alt = DataFrame(arr)
472+
tm.assert_frame_equal(alt, expected)

0 commit comments

Comments
 (0)