Skip to content

REGR: DataFrame(dict) missing columns should not be views #45432

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

Merged
merged 1 commit into from
Jan 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,13 @@ def dict_to_mgr(
# GH#1783
nan_dtype = np.dtype("object")
val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype)
arrays.loc[missing] = [val] * missing.sum()
nmissing = missing.sum()
if copy:
rhs = [val] * nmissing
else:
# GH#45369
rhs = [val.copy() for _ in range(nmissing)]
arrays.loc[missing] = rhs

arrays = list(arrays)
columns = ensure_index(columns)
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2642,6 +2642,23 @@ def test_error_from_2darray(self, col_a, col_b):
with pytest.raises(ValueError, match=msg):
DataFrame({"a": col_a, "b": col_b})

def test_from_dict_with_missing_copy_false(self):
# GH#45369 filled columns should not be views of one another
df = DataFrame(index=[1, 2, 3], columns=["a", "b", "c"], copy=False)
assert not np.shares_memory(df["a"]._values, df["b"]._values)

df.iloc[0, 0] = 0
expected = DataFrame(
{
"a": [0, np.nan, np.nan],
"b": [np.nan, np.nan, np.nan],
"c": [np.nan, np.nan, np.nan],
},
index=[1, 2, 3],
dtype=object,
)
tm.assert_frame_equal(df, expected)


class TestDataFrameConstructorIndexInference:
def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):
Expand Down