Skip to content

Commit a7c9877

Browse files
BUG: Pandas changes dtypes of columns when no float (or other) assignments are done to this column #34573 (#34599)
1 parent c860b4b commit a7c9877

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -897,6 +897,7 @@ Indexing
897897
- Bug in :meth:`DataFrame.truncate` and :meth:`Series.truncate` where index was assumed to be monotone increasing (:issue:`33756`)
898898
- Indexing with a list of strings representing datetimes failed on :class:`DatetimeIndex` or :class:`PeriodIndex`(:issue:`11278`)
899899
- Bug in :meth:`Series.at` when used with a :class:`MultiIndex` would raise an exception on valid inputs (:issue:`26989`)
900+
- Bug in :meth:`DataFrame.loc` with dictionary of values changes columns with dtype of ``int`` to ``float`` (:issue:`34573`)
900901
- Bug in :meth:`Series.loc` when used with a :class:`MultiIndex` would raise an IndexingError when accessing a None value (:issue:`34318`)
901902

902903
Missing

pandas/core/indexing.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1836,7 +1836,10 @@ def _setitem_with_indexer_missing(self, indexer, value):
18361836
# append a Series
18371837
value = value.reindex(index=self.obj.columns, copy=True)
18381838
value.name = indexer
1839-
1839+
elif isinstance(value, dict):
1840+
value = Series(
1841+
value, index=self.obj.columns, name=indexer, dtype=object
1842+
)
18401843
else:
18411844
# a list-list
18421845
if is_list_like_indexer(value):

pandas/tests/frame/indexing/test_setitem.py

+24
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,27 @@ def test_setitem_with_unaligned_sparse_value(self):
126126
df["new_column"] = sp_series
127127
expected = Series(SparseArray([1, 0, 0]), name="new_column")
128128
tm.assert_series_equal(df["new_column"], expected)
129+
130+
def test_setitem_dict_preserves_dtypes(self):
131+
# https://github.com/pandas-dev/pandas/issues/34573
132+
expected = DataFrame(
133+
{
134+
"a": Series([0, 1, 2], dtype="int64"),
135+
"b": Series([1, 2, 3], dtype=float),
136+
"c": Series([1, 2, 3], dtype=float),
137+
}
138+
)
139+
df = DataFrame(
140+
{
141+
"a": Series([], dtype="int64"),
142+
"b": Series([], dtype=float),
143+
"c": Series([], dtype=float),
144+
}
145+
)
146+
for idx, b in enumerate([1, 2, 3]):
147+
df.loc[df.shape[0]] = {
148+
"a": int(idx),
149+
"b": float(b),
150+
"c": float(b),
151+
}
152+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)