Skip to content

Commit c31a734

Browse files
Backport PR #45432: REGR: DataFrame(dict) missing columns should not be views (#45446)
Co-authored-by: jbrockmendel <[email protected]>
1 parent 4354b66 commit c31a734

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pandas/core/internals/construction.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,13 @@ def dict_to_mgr(
466466
# GH#1783
467467
nan_dtype = np.dtype("object")
468468
val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype)
469-
arrays.loc[missing] = [val] * missing.sum()
469+
nmissing = missing.sum()
470+
if copy:
471+
rhs = [val] * nmissing
472+
else:
473+
# GH#45369
474+
rhs = [val.copy() for _ in range(nmissing)]
475+
arrays.loc[missing] = rhs
470476

471477
arrays = list(arrays)
472478
columns = ensure_index(columns)

pandas/tests/frame/test_constructors.py

+17
Original file line numberDiff line numberDiff line change
@@ -2648,6 +2648,23 @@ def test_error_from_2darray(self, col_a, col_b):
26482648
with pytest.raises(ValueError, match=msg):
26492649
DataFrame({"a": col_a, "b": col_b})
26502650

2651+
def test_from_dict_with_missing_copy_false(self):
2652+
# GH#45369 filled columns should not be views of one another
2653+
df = DataFrame(index=[1, 2, 3], columns=["a", "b", "c"], copy=False)
2654+
assert not np.shares_memory(df["a"]._values, df["b"]._values)
2655+
2656+
df.iloc[0, 0] = 0
2657+
expected = DataFrame(
2658+
{
2659+
"a": [0, np.nan, np.nan],
2660+
"b": [np.nan, np.nan, np.nan],
2661+
"c": [np.nan, np.nan, np.nan],
2662+
},
2663+
index=[1, 2, 3],
2664+
dtype=object,
2665+
)
2666+
tm.assert_frame_equal(df, expected)
2667+
26512668

26522669
class TestDataFrameConstructorIndexInference:
26532670
def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):

0 commit comments

Comments
 (0)