Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/common.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/conftest.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_alter_axes.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_api.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_arrow_interface.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_block_internals.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_cumulative.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_iteration.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_logical_ops.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_nonunique_indexes.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_npfuncs.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_query_eval.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_repr.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_subclass.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_ufunc.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_unary.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_validate.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/constructors/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/frame/constructors/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_dict.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_records.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/constructors/test_from_dict.pyAdded+228
- lib/python3.12/site-packages/pandas/tests/frame/constructors/test_from_records.pyAdded+505
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_coercion.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_delitem.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_get.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_get_value.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_getitem.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_insert.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_mask.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_set_value.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_setitem.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_take.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_where.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_xs.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_coercion.pyAdded+199
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_delitem.pyAdded+60
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_get.pyAdded+27
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_get_value.pyAdded+22
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_getitem.pyAdded+472
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_indexing.pyAdded+2024
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_insert.pyAdded+120
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_mask.pyAdded+152
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_set_value.pyAdded+77
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_setitem.pyAdded+1419
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_take.pyAdded+92
- lib/python3.12/site-packages/pandas/tests/frame/indexing/test_where.pyAdded+1099
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228from collections import OrderedDict
import numpy as npimport pytest
from pandas._config import using_pyarrow_string_dtype
from pandas import ( DataFrame, Index, MultiIndex, RangeIndex, Series,)import pandas._testing as tm
class TestFromDict: # Note: these tests are specific to the from_dict method, not for # passing dictionaries to DataFrame.__init__
def test_constructor_list_of_odicts(self): data = [ OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]), OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]), OrderedDict([["a", 1.5], ["d", 6]]), OrderedDict(), OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), OrderedDict([["b", 3], ["c", 4], ["d", 6]]), ]
result = DataFrame(data) expected = DataFrame.from_dict( dict(zip(range(len(data)), data)), orient="index" ) tm.assert_frame_equal(result, expected.reindex(result.index))
def test_constructor_single_row(self): data = [OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]])]
result = DataFrame(data) expected = DataFrame.from_dict(dict(zip([0], data)), orient="index").reindex( result.index ) tm.assert_frame_equal(result, expected)
@pytest.mark.skipif( using_pyarrow_string_dtype(), reason="columns inferring logic broken" ) def test_constructor_list_of_series(self): data = [ OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]), OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]), ] sdict = OrderedDict(zip(["x", "y"], data)) idx = Index(["a", "b", "c"])
# all named data2 = [ Series([1.5, 3, 4], idx, dtype="O", name="x"), Series([1.5, 3, 6], idx, name="y"), ] result = DataFrame(data2) expected = DataFrame.from_dict(sdict, orient="index") tm.assert_frame_equal(result, expected)
# some unnamed data2 = [ Series([1.5, 3, 4], idx, dtype="O", name="x"), Series([1.5, 3, 6], idx), ] result = DataFrame(data2)
sdict = OrderedDict(zip(["x", "Unnamed 0"], data)) expected = DataFrame.from_dict(sdict, orient="index") tm.assert_frame_equal(result, expected)
# none named data = [ OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]), OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]), OrderedDict([["a", 1.5], ["d", 6]]), OrderedDict(), OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), OrderedDict([["b", 3], ["c", 4], ["d", 6]]), ] data = [Series(d) for d in data]
result = DataFrame(data) sdict = OrderedDict(zip(range(len(data)), data)) expected = DataFrame.from_dict(sdict, orient="index") tm.assert_frame_equal(result, expected.reindex(result.index))
result2 = DataFrame(data, index=np.arange(6, dtype=np.int64)) tm.assert_frame_equal(result, result2)
result = DataFrame([Series(dtype=object)]) expected = DataFrame(index=[0]) tm.assert_frame_equal(result, expected)
data = [ OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]), OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]), ] sdict = OrderedDict(zip(range(len(data)), data))
idx = Index(["a", "b", "c"]) data2 = [Series([1.5, 3, 4], idx, dtype="O"), Series([1.5, 3, 6], idx)] result = DataFrame(data2) expected = DataFrame.from_dict(sdict, orient="index") tm.assert_frame_equal(result, expected)
def test_constructor_orient(self, float_string_frame): data_dict = float_string_frame.T._series recons = DataFrame.from_dict(data_dict, orient="index") expected = float_string_frame.reindex(index=recons.index) tm.assert_frame_equal(recons, expected)
# dict of sequence a = {"hi": [32, 3, 3], "there": [3, 5, 3]} rs = DataFrame.from_dict(a, orient="index") xp = DataFrame.from_dict(a).T.reindex(list(a.keys())) tm.assert_frame_equal(rs, xp)
def test_constructor_from_ordered_dict(self): # GH#8425 a = OrderedDict( [ ("one", OrderedDict([("col_a", "foo1"), ("col_b", "bar1")])), ("two", OrderedDict([("col_a", "foo2"), ("col_b", "bar2")])), ("three", OrderedDict([("col_a", "foo3"), ("col_b", "bar3")])), ] ) expected = DataFrame.from_dict(a, orient="columns").T result = DataFrame.from_dict(a, orient="index") tm.assert_frame_equal(result, expected)
def test_from_dict_columns_parameter(self): # GH#18529 # Test new columns parameter for from_dict that was added to make # from_items(..., orient='index', columns=[...]) easier to replicate result = DataFrame.from_dict( OrderedDict([("A", [1, 2]), ("B", [4, 5])]), orient="index", columns=["one", "two"], ) expected = DataFrame([[1, 2], [4, 5]], index=["A", "B"], columns=["one", "two"]) tm.assert_frame_equal(result, expected)
msg = "cannot use columns parameter with orient='columns'" with pytest.raises(ValueError, match=msg): DataFrame.from_dict( {"A": [1, 2], "B": [4, 5]}, orient="columns", columns=["one", "two"], ) with pytest.raises(ValueError, match=msg): DataFrame.from_dict({"A": [1, 2], "B": [4, 5]}, columns=["one", "two"])
@pytest.mark.parametrize( "data_dict, orient, expected", [ ({}, "index", RangeIndex(0)), ( [{("a",): 1}, {("a",): 2}], "columns", Index([("a",)], tupleize_cols=False), ), ( [OrderedDict([(("a",), 1), (("b",), 2)])], "columns", Index([("a",), ("b",)], tupleize_cols=False), ), ([{("a", "b"): 1}], "columns", Index([("a", "b")], tupleize_cols=False)), ], ) def test_constructor_from_dict_tuples(self, data_dict, orient, expected): # GH#16769 df = DataFrame.from_dict(data_dict, orient) result = df.columns tm.assert_index_equal(result, expected)
def test_frame_dict_constructor_empty_series(self): s1 = Series( [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)]) ) s2 = Series( [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)]) ) s3 = Series(dtype=object)
# it works! DataFrame({"foo": s1, "bar": s2, "baz": s3}) DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2})
def test_from_dict_scalars_requires_index(self): msg = "If using all scalar values, you must pass an index" with pytest.raises(ValueError, match=msg): DataFrame.from_dict(OrderedDict([("b", 8), ("a", 5), ("a", 6)]))
def test_from_dict_orient_invalid(self): msg = ( "Expected 'index', 'columns' or 'tight' for orient parameter. " "Got 'abc' instead" ) with pytest.raises(ValueError, match=msg): DataFrame.from_dict({"foo": 1, "baz": 3, "bar": 2}, orient="abc")
def test_from_dict_order_with_single_column(self): data = { "alpha": { "value2": 123, "value1": 532, "animal": 222, "plant": False, "name": "test", } } result = DataFrame.from_dict( data, orient="columns", ) expected = DataFrame( [[123], [532], [222], [False], ["test"]], index=["value2", "value1", "animal", "plant", "name"], columns=["alpha"], ) tm.assert_frame_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505from collections.abc import Iteratorfrom datetime import datetimefrom decimal import Decimal
import numpy as npimport pytestimport pytz
from pandas._config import using_pyarrow_string_dtype
from pandas.compat import is_platform_little_endian
from pandas import ( CategoricalIndex, DataFrame, Index, Interval, RangeIndex, Series, date_range,)import pandas._testing as tm
class TestFromRecords: def test_from_records_dt64tz_frame(self): # GH#51162 don't lose tz when calling from_records with DataFrame input dti = date_range("2016-01-01", periods=10, tz="US/Pacific") df = DataFrame({i: dti for i in range(4)}) with tm.assert_produces_warning(FutureWarning): res = DataFrame.from_records(df) tm.assert_frame_equal(res, df)
def test_from_records_with_datetimes(self): # this may fail on certain platforms because of a numpy issue # related GH#6140 if not is_platform_little_endian(): pytest.skip("known failure of test on non-little endian")
# construction with a null in a recarray # GH#6140 expected = DataFrame({"EXPIRY": [datetime(2005, 3, 1, 0, 0), None]})
arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] dtypes = [("EXPIRY", "<M8[ns]")]
recarray = np.rec.fromarrays(arrdata, dtype=dtypes)
result = DataFrame.from_records(recarray) tm.assert_frame_equal(result, expected)
# coercion should work too arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] dtypes = [("EXPIRY", "<M8[m]")] recarray = np.rec.fromarrays(arrdata, dtype=dtypes) result = DataFrame.from_records(recarray) # we get the closest supported unit, "s" expected["EXPIRY"] = expected["EXPIRY"].astype("M8[s]") tm.assert_frame_equal(result, expected)
@pytest.mark.skipif( using_pyarrow_string_dtype(), reason="dtype checking logic doesn't work" ) def test_from_records_sequencelike(self): df = DataFrame( { "A": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float64 ), "A1": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float64 ), "B": np.array(np.arange(6), dtype=np.int64), "C": ["foo"] * 6, "D": np.array([True, False] * 3, dtype=bool), "E": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float32 ), "E1": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float32 ), "F": np.array(np.arange(6), dtype=np.int32), } )
# this is actually tricky to create the recordlike arrays and # have the dtypes be intact blocks = df._to_dict_of_blocks() tuples = [] columns = [] dtypes = [] for dtype, b in blocks.items(): columns.extend(b.columns) dtypes.extend([(c, np.dtype(dtype).descr[0][1]) for c in b.columns]) for i in range(len(df.index)): tup = [] for _, b in blocks.items(): tup.extend(b.iloc[i].values) tuples.append(tuple(tup))
recarray = np.array(tuples, dtype=dtypes).view(np.rec.recarray) recarray2 = df.to_records() lists = [list(x) for x in tuples]
# tuples (lose the dtype info) result = DataFrame.from_records(tuples, columns=columns).reindex( columns=df.columns )
# created recarray and with to_records recarray (have dtype info) result2 = DataFrame.from_records(recarray, columns=columns).reindex( columns=df.columns ) result3 = DataFrame.from_records(recarray2, columns=columns).reindex( columns=df.columns )
# list of tuples (no dtype info) result4 = DataFrame.from_records(lists, columns=columns).reindex( columns=df.columns )
tm.assert_frame_equal(result, df, check_dtype=False) tm.assert_frame_equal(result2, df) tm.assert_frame_equal(result3, df) tm.assert_frame_equal(result4, df, check_dtype=False)
# tuples is in the order of the columns result = DataFrame.from_records(tuples) tm.assert_index_equal(result.columns, RangeIndex(8))
# test exclude parameter & we are casting the results here (as we don't # have dtype info to recover) columns_to_test = [columns.index("C"), columns.index("E1")]
exclude = list(set(range(8)) - set(columns_to_test)) result = DataFrame.from_records(tuples, exclude=exclude) result.columns = [columns[i] for i in sorted(columns_to_test)] tm.assert_series_equal(result["C"], df["C"]) tm.assert_series_equal(result["E1"], df["E1"])
def test_from_records_sequencelike_empty(self): # empty case result = DataFrame.from_records([], columns=["foo", "bar", "baz"]) assert len(result) == 0 tm.assert_index_equal(result.columns, Index(["foo", "bar", "baz"]))
result = DataFrame.from_records([]) assert len(result) == 0 assert len(result.columns) == 0
def test_from_records_dictlike(self): # test the dict methods df = DataFrame( { "A": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float64 ), "A1": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float64 ), "B": np.array(np.arange(6), dtype=np.int64), "C": ["foo"] * 6, "D": np.array([True, False] * 3, dtype=bool), "E": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float32 ), "E1": np.array( np.random.default_rng(2).standard_normal(6), dtype=np.float32 ), "F": np.array(np.arange(6), dtype=np.int32), } )
# columns is in a different order here than the actual items iterated # from the dict blocks = df._to_dict_of_blocks() columns = [] for b in blocks.values(): columns.extend(b.columns)
asdict = dict(df.items()) asdict2 = {x: y.values for x, y in df.items()}
# dict of series & dict of ndarrays (have dtype info) results = [] results.append(DataFrame.from_records(asdict).reindex(columns=df.columns)) results.append( DataFrame.from_records(asdict, columns=columns).reindex(columns=df.columns) ) results.append( DataFrame.from_records(asdict2, columns=columns).reindex(columns=df.columns) )
for r in results: tm.assert_frame_equal(r, df)
def test_from_records_with_index_data(self): df = DataFrame( np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"] )
data = np.random.default_rng(2).standard_normal(10) with tm.assert_produces_warning(FutureWarning): df1 = DataFrame.from_records(df, index=data) tm.assert_index_equal(df1.index, Index(data))
def test_from_records_bad_index_column(self): df = DataFrame( np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"] )
# should pass with tm.assert_produces_warning(FutureWarning): df1 = DataFrame.from_records(df, index=["C"]) tm.assert_index_equal(df1.index, Index(df.C))
with tm.assert_produces_warning(FutureWarning): df1 = DataFrame.from_records(df, index="C") tm.assert_index_equal(df1.index, Index(df.C))
# should fail msg = "|".join( [ r"'None of \[2\] are in the columns'", ] ) with pytest.raises(KeyError, match=msg): with tm.assert_produces_warning(FutureWarning): DataFrame.from_records(df, index=[2]) with pytest.raises(KeyError, match=msg): with tm.assert_produces_warning(FutureWarning): DataFrame.from_records(df, index=2)
def test_from_records_non_tuple(self): class Record: def __init__(self, *args) -> None: self.args = args
def __getitem__(self, i): return self.args[i]
def __iter__(self) -> Iterator: return iter(self.args)
recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)] tups = [tuple(rec) for rec in recs]
result = DataFrame.from_records(recs) expected = DataFrame.from_records(tups) tm.assert_frame_equal(result, expected)
def test_from_records_len0_with_columns(self): # GH#2633 result = DataFrame.from_records([], index="foo", columns=["foo", "bar"]) expected = Index(["bar"])
assert len(result) == 0 assert result.index.name == "foo" tm.assert_index_equal(result.columns, expected)
def test_from_records_series_list_dict(self): # GH#27358 expected = DataFrame([[{"a": 1, "b": 2}, {"a": 3, "b": 4}]]).T data = Series([[{"a": 1, "b": 2}], [{"a": 3, "b": 4}]]) result = DataFrame.from_records(data) tm.assert_frame_equal(result, expected)
def test_from_records_series_categorical_index(self): # GH#32805 index = CategoricalIndex( [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)] ) series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index) frame = DataFrame.from_records(series_of_dicts, index=index) expected = DataFrame( {"a": [1, 2, np.nan], "b": [np.nan, np.nan, 3]}, index=index ) tm.assert_frame_equal(frame, expected)
def test_frame_from_records_utc(self): rec = {"datum": 1.5, "begin_time": datetime(2006, 4, 27, tzinfo=pytz.utc)}
# it works DataFrame.from_records([rec], index="begin_time")
def test_from_records_to_records(self): # from numpy documentation arr = np.zeros((2,), dtype=("i4,f4,S10")) arr[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")]
DataFrame.from_records(arr)
index = Index(np.arange(len(arr))[::-1]) indexed_frame = DataFrame.from_records(arr, index=index) tm.assert_index_equal(indexed_frame.index, index)
# without names, it should go to last ditch arr2 = np.zeros((2, 3)) tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))
# wrong length msg = "|".join( [ r"Length of values \(2\) does not match length of index \(1\)", ] ) with pytest.raises(ValueError, match=msg): DataFrame.from_records(arr, index=index[:-1])
indexed_frame = DataFrame.from_records(arr, index="f1")
# what to do? records = indexed_frame.to_records() assert len(records.dtype.names) == 3
records = indexed_frame.to_records(index=False) assert len(records.dtype.names) == 2 assert "index" not in records.dtype.names
def test_from_records_nones(self): tuples = [(1, 2, None, 3), (1, 2, None, 3), (None, 2, 5, 3)]
df = DataFrame.from_records(tuples, columns=["a", "b", "c", "d"]) assert np.isnan(df["c"][0])
def test_from_records_iterator(self): arr = np.array( [(1.0, 1.0, 2, 2), (3.0, 3.0, 4, 4), (5.0, 5.0, 6, 6), (7.0, 7.0, 8, 8)], dtype=[ ("x", np.float64), ("u", np.float32), ("y", np.int64), ("z", np.int32), ], ) df = DataFrame.from_records(iter(arr), nrows=2) xp = DataFrame( { "x": np.array([1.0, 3.0], dtype=np.float64), "u": np.array([1.0, 3.0], dtype=np.float32), "y": np.array([2, 4], dtype=np.int64), "z": np.array([2, 4], dtype=np.int32), } ) tm.assert_frame_equal(df.reindex_like(xp), xp)
# no dtypes specified here, so just compare with the default arr = [(1.0, 2), (3.0, 4), (5.0, 6), (7.0, 8)] df = DataFrame.from_records(iter(arr), columns=["x", "y"], nrows=2) tm.assert_frame_equal(df, xp.reindex(columns=["x", "y"]), check_dtype=False)
def test_from_records_tuples_generator(self): def tuple_generator(length): for i in range(length): letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" yield (i, letters[i % len(letters)], i / length)
columns_names = ["Integer", "String", "Float"] columns = [ [i[j] for i in tuple_generator(10)] for j in range(len(columns_names)) ] data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]} expected = DataFrame(data, columns=columns_names)
generator = tuple_generator(10) result = DataFrame.from_records(generator, columns=columns_names) tm.assert_frame_equal(result, expected)
def test_from_records_lists_generator(self): def list_generator(length): for i in range(length): letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" yield [i, letters[i % len(letters)], i / length]
columns_names = ["Integer", "String", "Float"] columns = [ [i[j] for i in list_generator(10)] for j in range(len(columns_names)) ] data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]} expected = DataFrame(data, columns=columns_names)
generator = list_generator(10) result = DataFrame.from_records(generator, columns=columns_names) tm.assert_frame_equal(result, expected)
def test_from_records_columns_not_modified(self): tuples = [(1, 2, 3), (1, 2, 3), (2, 5, 3)]
columns = ["a", "b", "c"] original_columns = list(columns)
DataFrame.from_records(tuples, columns=columns, index="a")
assert columns == original_columns
def test_from_records_decimal(self): tuples = [(Decimal("1.5"),), (Decimal("2.5"),), (None,)]
df = DataFrame.from_records(tuples, columns=["a"]) assert df["a"].dtype == object
df = DataFrame.from_records(tuples, columns=["a"], coerce_float=True) assert df["a"].dtype == np.float64 assert np.isnan(df["a"].values[-1])
def test_from_records_duplicates(self): result = DataFrame.from_records([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"])
expected = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"])
tm.assert_frame_equal(result, expected)
def test_from_records_set_index_name(self): def create_dict(order_id): return { "order_id": order_id, "quantity": np.random.default_rng(2).integers(1, 10), "price": np.random.default_rng(2).integers(1, 10), }
documents = [create_dict(i) for i in range(10)] # demo missing data documents.append({"order_id": 10, "quantity": 5})
result = DataFrame.from_records(documents, index="order_id") assert result.index.name == "order_id"
# MultiIndex result = DataFrame.from_records(documents, index=["order_id", "quantity"]) assert result.index.names == ("order_id", "quantity")
def test_from_records_misc_brokenness(self): # GH#2179
data = {1: ["foo"], 2: ["bar"]}
result = DataFrame.from_records(data, columns=["a", "b"]) exp = DataFrame(data, columns=["a", "b"]) tm.assert_frame_equal(result, exp)
# overlap in index/index_names
data = {"a": [1, 2, 3], "b": [4, 5, 6]}
result = DataFrame.from_records(data, index=["a", "b", "c"]) exp = DataFrame(data, index=["a", "b", "c"]) tm.assert_frame_equal(result, exp)
def test_from_records_misc_brokenness2(self): # GH#2623 rows = [] rows.append([datetime(2010, 1, 1), 1]) rows.append([datetime(2010, 1, 2), "hi"]) # test col upconverts to obj result = DataFrame.from_records(rows, columns=["date", "test"]) expected = DataFrame( {"date": [row[0] for row in rows], "test": [row[1] for row in rows]} ) tm.assert_frame_equal(result, expected) assert result.dtypes["test"] == np.dtype(object)
def test_from_records_misc_brokenness3(self): rows = [] rows.append([datetime(2010, 1, 1), 1]) rows.append([datetime(2010, 1, 2), 1]) result = DataFrame.from_records(rows, columns=["date", "test"]) expected = DataFrame( {"date": [row[0] for row in rows], "test": [row[1] for row in rows]} ) tm.assert_frame_equal(result, expected)
def test_from_records_empty(self): # GH#3562 result = DataFrame.from_records([], columns=["a", "b", "c"]) expected = DataFrame(columns=["a", "b", "c"]) tm.assert_frame_equal(result, expected)
result = DataFrame.from_records([], columns=["a", "b", "b"]) expected = DataFrame(columns=["a", "b", "b"]) tm.assert_frame_equal(result, expected)
def test_from_records_empty_with_nonempty_fields_gh3682(self): a = np.array([(1, 2)], dtype=[("id", np.int64), ("value", np.int64)]) df = DataFrame.from_records(a, index="id")
ex_index = Index([1], name="id") expected = DataFrame({"value": [2]}, index=ex_index, columns=["value"]) tm.assert_frame_equal(df, expected)
b = a[:0] df2 = DataFrame.from_records(b, index="id") tm.assert_frame_equal(df2, df.iloc[:0])
def test_from_records_empty2(self): # GH#42456 dtype = [("prop", int)] shape = (0, len(dtype)) arr = np.empty(shape, dtype=dtype)
result = DataFrame.from_records(arr) expected = DataFrame({"prop": np.array([], dtype=int)}) tm.assert_frame_equal(result, expected)
alt = DataFrame(arr) tm.assert_frame_equal(alt, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199"""Tests for values coercion in setitem-like operations on DataFrame.
For the most part, these should be multi-column DataFrames, otherwisewe would share the tests with Series."""import numpy as npimport pytest
import pandas as pdfrom pandas import ( DataFrame, MultiIndex, NaT, Series, Timestamp, date_range,)import pandas._testing as tm
class TestDataFrameSetitemCoercion: @pytest.mark.parametrize("consolidate", [True, False]) def test_loc_setitem_multiindex_columns(self, consolidate): # GH#18415 Setting values in a single column preserves dtype, # while setting them in multiple columns did unwanted cast.
# Note that A here has 2 blocks, below we do the same thing # with a consolidated frame. A = DataFrame(np.zeros((6, 5), dtype=np.float32)) A = pd.concat([A, A], axis=1, keys=[1, 2]) if consolidate: A = A._consolidate()
A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32) assert (A.dtypes == np.float32).all()
A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
assert (A.dtypes == np.float32).all()
A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32) assert (A.dtypes == np.float32).all()
# TODO: i think this isn't about MultiIndex and could be done with iloc?
def test_37477(): # fixed by GH#45121 orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]}) expected = DataFrame({"A": [1, 2, 3], "B": [3, 1.2, 5]})
df = orig.copy() with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.at[1, "B"] = 1.2 tm.assert_frame_equal(df, expected)
df = orig.copy() with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.loc[1, "B"] = 1.2 tm.assert_frame_equal(df, expected)
df = orig.copy() with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.iat[1, 1] = 1.2 tm.assert_frame_equal(df, expected)
df = orig.copy() with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.iloc[1, 1] = 1.2 tm.assert_frame_equal(df, expected)
def test_6942(indexer_al): # check that the .at __setitem__ after setting "Live" actually sets the data start = Timestamp("2014-04-01") t1 = Timestamp("2014-04-23 12:42:38.883082") t2 = Timestamp("2014-04-24 01:33:30.040039")
dti = date_range(start, periods=1) orig = DataFrame(index=dti, columns=["timenow", "Live"])
df = orig.copy() indexer_al(df)[start, "timenow"] = t1
df["Live"] = True
df.at[start, "timenow"] = t2 assert df.iloc[0, 0] == t2
def test_26395(indexer_al): # .at case fixed by GH#45121 (best guess) df = DataFrame(index=["A", "B", "C"]) df["D"] = 0
indexer_al(df)["C", "D"] = 2 expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64) tm.assert_frame_equal(df, expected)
with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): indexer_al(df)["C", "D"] = 44.5 expected = DataFrame({"D": [0, 0, 44.5]}, index=["A", "B", "C"], dtype=np.float64) tm.assert_frame_equal(df, expected)
with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): indexer_al(df)["C", "D"] = "hello" expected = DataFrame({"D": [0, 0, "hello"]}, index=["A", "B", "C"], dtype=object) tm.assert_frame_equal(df, expected)
@pytest.mark.xfail(reason="unwanted upcast")def test_15231(): df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) df.loc[2] = Series({"a": 5, "b": 6}) assert (df.dtypes == np.int64).all()
df.loc[3] = Series({"a": 7})
# df["a"] doesn't have any NaNs, should not have been cast exp_dtypes = Series([np.int64, np.float64], dtype=object, index=["a", "b"]) tm.assert_series_equal(df.dtypes, exp_dtypes)
def test_iloc_setitem_unnecesssary_float_upcasting(): # GH#12255 df = DataFrame( { 0: np.array([1, 3], dtype=np.float32), 1: np.array([2, 4], dtype=np.float32), 2: ["a", "b"], } ) orig = df.copy()
values = df[0].values.reshape(2, 1) df.iloc[:, 0:1] = values
tm.assert_frame_equal(df, orig)
@pytest.mark.xfail(reason="unwanted casting to dt64")def test_12499(): # TODO: OP in GH#12499 used np.datetim64("NaT") instead of pd.NaT, # which has consequences for the expected df["two"] (though i think at # the time it might not have because of a separate bug). See if it makes # a difference which one we use here. ts = Timestamp("2016-03-01 03:13:22.98986", tz="UTC")
data = [{"one": 0, "two": ts}] orig = DataFrame(data) df = orig.copy() df.loc[1] = [np.nan, NaT]
expected = DataFrame( {"one": [0, np.nan], "two": Series([ts, NaT], dtype="datetime64[ns, UTC]")} ) tm.assert_frame_equal(df, expected)
data = [{"one": 0, "two": ts}] df = orig.copy() df.loc[1, :] = [np.nan, NaT] tm.assert_frame_equal(df, expected)
def test_20476(): mi = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]]) df = DataFrame(-1, index=range(3), columns=mi) filler = DataFrame([[1, 2, 3.0]] * 3, index=range(3), columns=["a", "b", "c"]) df["A"] = filler
expected = DataFrame( { 0: [1, 1, 1], 1: [2, 2, 2], 2: [3.0, 3.0, 3.0], 3: [-1, -1, -1], 4: [-1, -1, -1], 5: [-1, -1, -1], } ) expected.columns = mi exp_dtypes = Series( [np.dtype(np.int64)] * 2 + [np.dtype(np.float64)] + [np.dtype(np.int64)] * 3, index=mi, ) tm.assert_series_equal(df.dtypes, exp_dtypes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import re
import numpy as npimport pytest
from pandas import ( DataFrame, MultiIndex,)
class TestDataFrameDelItem: def test_delitem(self, float_frame): del float_frame["A"] assert "A" not in float_frame
def test_delitem_multiindex(self): midx = MultiIndex.from_product([["A", "B"], [1, 2]]) df = DataFrame(np.random.default_rng(2).standard_normal((4, 4)), columns=midx) assert len(df.columns) == 4 assert ("A",) in df.columns assert "A" in df.columns
result = df["A"] assert isinstance(result, DataFrame) del df["A"]
assert len(df.columns) == 2
# A still in the levels, BUT get a KeyError if trying # to delete assert ("A",) not in df.columns with pytest.raises(KeyError, match=re.escape("('A',)")): del df[("A",)]
# behavior of dropped/deleted MultiIndex levels changed from # GH 2770 to GH 19027: MultiIndex no longer '.__contains__' # levels which are dropped/deleted assert "A" not in df.columns with pytest.raises(KeyError, match=re.escape("('A',)")): del df["A"]
def test_delitem_corner(self, float_frame): f = float_frame.copy() del f["D"] assert len(f.columns) == 3 with pytest.raises(KeyError, match=r"^'D'$"): del f["D"] del f["B"] assert len(f.columns) == 2
def test_delitem_col_still_multiindex(self): arrays = [["a", "b", "c", "top"], ["", "", "", "OD"], ["", "", "", "wx"]]
tuples = sorted(zip(*arrays)) index = MultiIndex.from_tuples(tuples)
df = DataFrame(np.random.default_rng(2).standard_normal((3, 4)), columns=index) del df[("a", "", "")] assert isinstance(df.columns, MultiIndex)123456789101112131415161718192021222324252627import pytest
from pandas import DataFrameimport pandas._testing as tm
class TestGet: def test_get(self, float_frame): b = float_frame.get("B") tm.assert_series_equal(b, float_frame["B"])
assert float_frame.get("foo") is None tm.assert_series_equal( float_frame.get("foo", float_frame["B"]), float_frame["B"] )
@pytest.mark.parametrize( "df", [ DataFrame(), DataFrame(columns=list("AB")), DataFrame(columns=list("AB"), index=range(3)), ], ) def test_get_none(self, df): # see gh-5652 assert df.get(None) is None12345678910111213141516171819202122import pytest
from pandas import ( DataFrame, MultiIndex,)
class TestGetValue: def test_get_set_value_no_partial_indexing(self): # partial w/ MultiIndex raise exception index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)]) df = DataFrame(index=index, columns=range(4)) with pytest.raises(KeyError, match=r"^0$"): df._get_value(0, 1)
def test_get_value(self, float_frame): for idx in float_frame.index: for col in float_frame.columns: result = float_frame._get_value(idx, col) expected = float_frame[col][idx] assert result == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472import re
import numpy as npimport pytest
from pandas import ( Categorical, CategoricalDtype, CategoricalIndex, DataFrame, DateOffset, DatetimeIndex, Index, MultiIndex, Series, Timestamp, concat, date_range, get_dummies, period_range,)import pandas._testing as tmfrom pandas.core.arrays import SparseArray
class TestGetitem: def test_getitem_unused_level_raises(self): # GH#20410 mi = MultiIndex( levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]], codes=[[1, 0], [1, 0]], ) df = DataFrame(-1, index=range(3), columns=mi)
with pytest.raises(KeyError, match="notevenone"): df["notevenone"]
def test_getitem_periodindex(self): rng = period_range("1/1/2000", periods=5) df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)), columns=rng)
ts = df[rng[0]] tm.assert_series_equal(ts, df.iloc[:, 0])
ts = df["1/1/2000"] tm.assert_series_equal(ts, df.iloc[:, 0])
def test_getitem_list_of_labels_categoricalindex_cols(self): # GH#16115 cats = Categorical([Timestamp("12-31-1999"), Timestamp("12-31-2000")])
expected = DataFrame([[1, 0], [0, 1]], dtype="bool", index=[0, 1], columns=cats) dummies = get_dummies(cats) result = dummies[list(dummies.columns)] tm.assert_frame_equal(result, expected)
def test_getitem_sparse_column_return_type_and_dtype(self): # https://github.com/pandas-dev/pandas/issues/23559 data = SparseArray([0, 1]) df = DataFrame({"A": data}) expected = Series(data, name="A") result = df["A"] tm.assert_series_equal(result, expected)
# Also check iloc and loc while we're here result = df.iloc[:, 0] tm.assert_series_equal(result, expected)
result = df.loc[:, "A"] tm.assert_series_equal(result, expected)
def test_getitem_string_columns(self): # GH#46185 df = DataFrame([[1, 2]], columns=Index(["A", "B"], dtype="string")) result = df.A expected = df["A"] tm.assert_series_equal(result, expected)
class TestGetitemListLike: def test_getitem_list_missing_key(self): # GH#13822, incorrect error string with non-unique columns when missing # column is accessed df = DataFrame({"x": [1.0], "y": [2.0], "z": [3.0]}) df.columns = ["x", "x", "z"]
# Check that we get the correct value in the KeyError with pytest.raises(KeyError, match=r"\['y'\] not in index"): df[["x", "y", "z"]]
def test_getitem_list_duplicates(self): # GH#1943 df = DataFrame( np.random.default_rng(2).standard_normal((4, 4)), columns=list("AABC") ) df.columns.name = "foo"
result = df[["B", "C"]] assert result.columns.name == "foo"
expected = df.iloc[:, 2:] tm.assert_frame_equal(result, expected)
def test_getitem_dupe_cols(self): df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) msg = "\"None of [Index(['baf'], dtype=" with pytest.raises(KeyError, match=re.escape(msg)): df[["baf"]]
@pytest.mark.parametrize( "idx_type", [ list, iter, Index, set, lambda keys: dict(zip(keys, range(len(keys)))), lambda keys: dict(zip(keys, range(len(keys)))).keys(), ], ids=["list", "iter", "Index", "set", "dict", "dict_keys"], ) @pytest.mark.parametrize("levels", [1, 2]) def test_getitem_listlike(self, idx_type, levels, float_frame): # GH#21294
if levels == 1: frame, missing = float_frame, "food" else: # MultiIndex columns frame = DataFrame( np.random.default_rng(2).standard_normal((8, 3)), columns=Index( [("foo", "bar"), ("baz", "qux"), ("peek", "aboo")], name=("sth", "sth2"), ), ) missing = ("good", "food")
keys = [frame.columns[1], frame.columns[0]] idx = idx_type(keys) idx_check = list(idx_type(keys))
if isinstance(idx, (set, dict)): with pytest.raises(TypeError, match="as an indexer is not supported"): frame[idx]
return else: result = frame[idx]
expected = frame.loc[:, idx_check] expected.columns.names = frame.columns.names
tm.assert_frame_equal(result, expected)
idx = idx_type(keys + [missing]) with pytest.raises(KeyError, match="not in index"): frame[idx]
def test_getitem_iloc_generator(self): # GH#39614 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) indexer = (x for x in [1, 2]) result = df.iloc[indexer] expected = DataFrame({"a": [2, 3], "b": [5, 6]}, index=[1, 2]) tm.assert_frame_equal(result, expected)
def test_getitem_iloc_two_dimensional_generator(self): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) indexer = (x for x in [1, 2]) result = df.iloc[indexer, 1] expected = Series([5, 6], name="b", index=[1, 2]) tm.assert_series_equal(result, expected)
def test_getitem_iloc_dateoffset_days(self): # GH 46671 df = DataFrame( list(range(10)), index=date_range("01-01-2022", periods=10, freq=DateOffset(days=1)), ) result = df.loc["2022-01-01":"2022-01-03"] expected = DataFrame( [0, 1, 2], index=DatetimeIndex( ["2022-01-01", "2022-01-02", "2022-01-03"], dtype="datetime64[ns]", freq=DateOffset(days=1), ), ) tm.assert_frame_equal(result, expected)
df = DataFrame( list(range(10)), index=date_range( "01-01-2022", periods=10, freq=DateOffset(days=1, hours=2) ), ) result = df.loc["2022-01-01":"2022-01-03"] expected = DataFrame( [0, 1, 2], index=DatetimeIndex( ["2022-01-01 00:00:00", "2022-01-02 02:00:00", "2022-01-03 04:00:00"], dtype="datetime64[ns]", freq=DateOffset(days=1, hours=2), ), ) tm.assert_frame_equal(result, expected)
df = DataFrame( list(range(10)), index=date_range("01-01-2022", periods=10, freq=DateOffset(minutes=3)), ) result = df.loc["2022-01-01":"2022-01-03"] tm.assert_frame_equal(result, df)
class TestGetitemCallable: def test_getitem_callable(self, float_frame): # GH#12533 result = float_frame[lambda x: "A"] expected = float_frame.loc[:, "A"] tm.assert_series_equal(result, expected)
result = float_frame[lambda x: ["A", "B"]] expected = float_frame.loc[:, ["A", "B"]] tm.assert_frame_equal(result, float_frame.loc[:, ["A", "B"]])
df = float_frame[:3] result = df[lambda x: [True, False, True]] expected = float_frame.iloc[[0, 2], :] tm.assert_frame_equal(result, expected)
def test_loc_multiindex_columns_one_level(self): # GH#29749 df = DataFrame([[1, 2]], columns=[["a", "b"]]) expected = DataFrame([1], columns=[["a"]])
result = df["a"] tm.assert_frame_equal(result, expected)
result = df.loc[:, "a"] tm.assert_frame_equal(result, expected)
class TestGetitemBooleanMask: def test_getitem_bool_mask_categorical_index(self): df3 = DataFrame( { "A": np.arange(6, dtype="int64"), }, index=CategoricalIndex( [1, 1, 2, 1, 3, 2], dtype=CategoricalDtype([3, 2, 1], ordered=True), name="B", ), ) df4 = DataFrame( { "A": np.arange(6, dtype="int64"), }, index=CategoricalIndex( [1, 1, 2, 1, 3, 2], dtype=CategoricalDtype([3, 2, 1], ordered=False), name="B", ), )
result = df3[df3.index == "a"] expected = df3.iloc[[]] tm.assert_frame_equal(result, expected)
result = df4[df4.index == "a"] expected = df4.iloc[[]] tm.assert_frame_equal(result, expected)
result = df3[df3.index == 1] expected = df3.iloc[[0, 1, 3]] tm.assert_frame_equal(result, expected)
result = df4[df4.index == 1] expected = df4.iloc[[0, 1, 3]] tm.assert_frame_equal(result, expected)
# since we have an ordered categorical
# CategoricalIndex([1, 1, 2, 1, 3, 2], # categories=[3, 2, 1], # ordered=True, # name='B') result = df3[df3.index < 2] expected = df3.iloc[[4]] tm.assert_frame_equal(result, expected)
result = df3[df3.index > 1] expected = df3.iloc[[]] tm.assert_frame_equal(result, expected)
# unordered # cannot be compared
# CategoricalIndex([1, 1, 2, 1, 3, 2], # categories=[3, 2, 1], # ordered=False, # name='B') msg = "Unordered Categoricals can only compare equality or not" with pytest.raises(TypeError, match=msg): df4[df4.index < 2] with pytest.raises(TypeError, match=msg): df4[df4.index > 1]
@pytest.mark.parametrize( "data1,data2,expected_data", ( ( [[1, 2], [3, 4]], [[0.5, 6], [7, 8]], [[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]], ), ( [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]], ), ), ) def test_getitem_bool_mask_duplicate_columns_mixed_dtypes( self, data1, data2, expected_data, ): # GH#31954
df1 = DataFrame(np.array(data1)) df2 = DataFrame(np.array(data2)) df = concat([df1, df2], axis=1)
result = df[df > 2]
exdict = {i: np.array(col) for i, col in enumerate(expected_data)} expected = DataFrame(exdict).rename(columns={2: 0, 3: 1}) tm.assert_frame_equal(result, expected)
@pytest.fixture def df_dup_cols(self): dups = ["A", "A", "C", "D"] df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") return df
def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_cols): # `df.A > 6` is a DataFrame with a different shape from df
# boolean with the duplicate raises df = df_dup_cols msg = "cannot reindex on an axis with duplicate labels" with pytest.raises(ValueError, match=msg): df[df.A > 6]
def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols): # boolean indexing # GH#4879 df = DataFrame( np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" ) expected = df[df.C > 6] expected.columns = df_dup_cols.columns
df = df_dup_cols result = df[df.C > 6]
tm.assert_frame_equal(result, expected)
def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols): # where df = DataFrame( np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" ) # `df > 6` is a DataFrame with the same shape+alignment as df expected = df[df > 6] expected.columns = df_dup_cols.columns
df = df_dup_cols result = df[df > 6]
tm.assert_frame_equal(result, expected)
def test_getitem_empty_frame_with_boolean(self): # Test for issue GH#11859
df = DataFrame() df2 = df[df > 0] tm.assert_frame_equal(df, df2)
def test_getitem_returns_view_when_column_is_unique_in_df( self, using_copy_on_write, warn_copy_on_write ): # GH#45316 df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) df_orig = df.copy() view = df["b"] with tm.assert_cow_warning(warn_copy_on_write): view.loc[:] = 100 if using_copy_on_write: expected = df_orig else: expected = DataFrame([[1, 2, 100], [4, 5, 100]], columns=["a", "a", "b"]) tm.assert_frame_equal(df, expected)
def test_getitem_frozenset_unique_in_column(self): # GH#41062 df = DataFrame([[1, 2, 3, 4]], columns=[frozenset(["KEY"]), "B", "C", "C"]) result = df[frozenset(["KEY"])] expected = Series([1], name=frozenset(["KEY"])) tm.assert_series_equal(result, expected)
class TestGetitemSlice: def test_getitem_slice_float64(self, frame_or_series): values = np.arange(10.0, 50.0, 2) index = Index(values)
start, end = values[[5, 15]]
data = np.random.default_rng(2).standard_normal((20, 3)) if frame_or_series is not DataFrame: data = data[:, 0]
obj = frame_or_series(data, index=index)
result = obj[start:end] expected = obj.iloc[5:16] tm.assert_equal(result, expected)
result = obj.loc[start:end] tm.assert_equal(result, expected)
def test_getitem_datetime_slice(self): # GH#43223 df = DataFrame( {"a": 0}, index=DatetimeIndex( [ "11.01.2011 22:00", "11.01.2011 23:00", "12.01.2011 00:00", "2011-01-13 00:00", ] ), ) with pytest.raises( KeyError, match="Value based partial slicing on non-monotonic" ): df["2011-01-01":"2011-11-01"]
def test_getitem_slice_same_dim_only_one_axis(self): # GH#54622 df = DataFrame(np.random.default_rng(2).standard_normal((10, 8))) result = df.iloc[(slice(None, None, 2),)] assert result.shape == (5, 8) expected = df.iloc[slice(None, None, 2), slice(None)] tm.assert_frame_equal(result, expected)
class TestGetitemDeprecatedIndexers: @pytest.mark.parametrize("key", [{"a", "b"}, {"a": "a"}]) def test_getitem_dict_and_set_deprecated(self, key): # GH#42825 enforced in 2.0 df = DataFrame( [[1, 2], [3, 4]], columns=MultiIndex.from_tuples([("a", 1), ("b", 2)]) ) with pytest.raises(TypeError, match="as an indexer is not supported"): df[key]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024from collections import namedtuplefrom datetime import ( datetime, timedelta,)from decimal import Decimalimport re
import numpy as npimport pytest
from pandas._libs import iNaTfrom pandas.errors import ( InvalidIndexError, PerformanceWarning, SettingWithCopyError,)import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_integer
import pandas as pdfrom pandas import ( Categorical, DataFrame, DatetimeIndex, Index, MultiIndex, Series, Timestamp, date_range, isna, notna, to_datetime,)import pandas._testing as tm
# We pass through a TypeError raised by numpy_slice_msg = "slice indices must be integers or None or have an __index__ method"
class TestDataFrameIndexing: def test_getitem(self, float_frame): # Slicing sl = float_frame[:20] assert len(sl.index) == 20
# Column access for _, series in sl.items(): assert len(series.index) == 20 tm.assert_index_equal(series.index, sl.index)
for key, _ in float_frame._series.items(): assert float_frame[key] is not None
assert "random" not in float_frame with pytest.raises(KeyError, match="random"): float_frame["random"]
def test_getitem_numeric_should_not_fallback_to_positional(self, any_numeric_dtype): # GH51053 dtype = any_numeric_dtype idx = Index([1, 0, 1], dtype=dtype) df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=idx) result = df[1] expected = DataFrame([[1, 3], [4, 6]], columns=Index([1, 1], dtype=dtype)) tm.assert_frame_equal(result, expected, check_exact=True)
def test_getitem2(self, float_frame): df = float_frame.copy() df["$10"] = np.random.default_rng(2).standard_normal(len(df))
ad = np.random.default_rng(2).standard_normal(len(df)) df["@awesome_domain"] = ad
with pytest.raises(KeyError, match=re.escape("'df[\"$10\"]'")): df.__getitem__('df["$10"]')
res = df["@awesome_domain"] tm.assert_numpy_array_equal(ad, res.values)
def test_setitem_numeric_should_not_fallback_to_positional(self, any_numeric_dtype): # GH51053 dtype = any_numeric_dtype idx = Index([1, 0, 1], dtype=dtype) df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=idx) df[1] = 10 expected = DataFrame([[10, 2, 10], [10, 5, 10]], columns=idx) tm.assert_frame_equal(df, expected, check_exact=True)
def test_setitem_list(self, float_frame): float_frame["E"] = "foo" data = float_frame[["A", "B"]] float_frame[["B", "A"]] = data
tm.assert_series_equal(float_frame["B"], data["A"], check_names=False) tm.assert_series_equal(float_frame["A"], data["B"], check_names=False)
msg = "Columns must be same length as key" with pytest.raises(ValueError, match=msg): data[["A"]] = float_frame[["A", "B"]] newcolumndata = range(len(data.index) - 1) msg = ( rf"Length of values \({len(newcolumndata)}\) " rf"does not match length of index \({len(data)}\)" ) with pytest.raises(ValueError, match=msg): data["A"] = newcolumndata
def test_setitem_list2(self): df = DataFrame(0, index=range(3), columns=["tt1", "tt2"], dtype=int) df.loc[1, ["tt1", "tt2"]] = [1, 2]
result = df.loc[df.index[1], ["tt1", "tt2"]] expected = Series([1, 2], df.columns, dtype=int, name=1) tm.assert_series_equal(result, expected)
df["tt1"] = df["tt2"] = "0" df.loc[df.index[1], ["tt1", "tt2"]] = ["1", "2"] result = df.loc[df.index[1], ["tt1", "tt2"]] expected = Series(["1", "2"], df.columns, name=1) tm.assert_series_equal(result, expected)
def test_getitem_boolean(self, mixed_float_frame, mixed_int_frame, datetime_frame): # boolean indexing d = datetime_frame.index[10] indexer = datetime_frame.index > d indexer_obj = indexer.astype(object)
subindex = datetime_frame.index[indexer] subframe = datetime_frame[indexer]
tm.assert_index_equal(subindex, subframe.index) with pytest.raises(ValueError, match="Item wrong length"): datetime_frame[indexer[:-1]]
subframe_obj = datetime_frame[indexer_obj] tm.assert_frame_equal(subframe_obj, subframe)
with pytest.raises(ValueError, match="Boolean array expected"): datetime_frame[datetime_frame]
# test that Series work indexer_obj = Series(indexer_obj, datetime_frame.index)
subframe_obj = datetime_frame[indexer_obj] tm.assert_frame_equal(subframe_obj, subframe)
# test that Series indexers reindex # we are producing a warning that since the passed boolean # key is not the same as the given index, we will reindex # not sure this is really necessary with tm.assert_produces_warning(UserWarning): indexer_obj = indexer_obj.reindex(datetime_frame.index[::-1]) subframe_obj = datetime_frame[indexer_obj] tm.assert_frame_equal(subframe_obj, subframe)
# test df[df > 0] for df in [ datetime_frame, mixed_float_frame, mixed_int_frame, ]: data = df._get_numeric_data() bif = df[df > 0] bifw = DataFrame( {c: np.where(data[c] > 0, data[c], np.nan) for c in data.columns}, index=data.index, columns=data.columns, )
# add back other columns to compare for c in df.columns: if c not in bifw: bifw[c] = df[c] bifw = bifw.reindex(columns=df.columns)
tm.assert_frame_equal(bif, bifw, check_dtype=False) for c in df.columns: if bif[c].dtype != bifw[c].dtype: assert bif[c].dtype == df[c].dtype
def test_getitem_boolean_casting(self, datetime_frame): # don't upcast if we don't need to df = datetime_frame.copy() df["E"] = 1 df["E"] = df["E"].astype("int32") df["E1"] = df["E"].copy() df["F"] = 1 df["F"] = df["F"].astype("int64") df["F1"] = df["F"].copy()
casted = df[df > 0] result = casted.dtypes expected = Series( [np.dtype("float64")] * 4 + [np.dtype("int32")] * 2 + [np.dtype("int64")] * 2, index=["A", "B", "C", "D", "E", "E1", "F", "F1"], ) tm.assert_series_equal(result, expected)
# int block splitting df.loc[df.index[1:3], ["E1", "F1"]] = 0 casted = df[df > 0] result = casted.dtypes expected = Series( [np.dtype("float64")] * 4 + [np.dtype("int32")] + [np.dtype("float64")] + [np.dtype("int64")] + [np.dtype("float64")], index=["A", "B", "C", "D", "E", "E1", "F", "F1"], ) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "lst", [[True, False, True], [True, True, True], [False, False, False]] ) def test_getitem_boolean_list(self, lst): df = DataFrame(np.arange(12).reshape(3, 4)) result = df[lst] expected = df.loc[df.index[lst]] tm.assert_frame_equal(result, expected)
def test_getitem_boolean_iadd(self): arr = np.random.default_rng(2).standard_normal((5, 5))
df = DataFrame(arr.copy(), columns=["A", "B", "C", "D", "E"])
df[df < 0] += 1 arr[arr < 0] += 1
tm.assert_almost_equal(df.values, arr)
def test_boolean_index_empty_corner(self): # #2096 blah = DataFrame(np.empty([0, 1]), columns=["A"], index=DatetimeIndex([]))
# both of these should succeed trivially k = np.array([], bool)
blah[k] blah[k] = 0
def test_getitem_ix_mixed_integer(self): df = DataFrame( np.random.default_rng(2).standard_normal((4, 3)), index=[1, 10, "C", "E"], columns=[1, 2, 3], )
result = df.iloc[:-1] expected = df.loc[df.index[:-1]] tm.assert_frame_equal(result, expected)
result = df.loc[[1, 10]] expected = df.loc[Index([1, 10])] tm.assert_frame_equal(result, expected)
def test_getitem_ix_mixed_integer2(self): # 11320 df = DataFrame( { "rna": (1.5, 2.2, 3.2, 4.5), -1000: [11, 21, 36, 40], 0: [10, 22, 43, 34], 1000: [0, 10, 20, 30], }, columns=["rna", -1000, 0, 1000], ) result = df[[1000]] expected = df.iloc[:, [3]] tm.assert_frame_equal(result, expected) result = df[[-1000]] expected = df.iloc[:, [1]] tm.assert_frame_equal(result, expected)
def test_getattr(self, float_frame): tm.assert_series_equal(float_frame.A, float_frame["A"]) msg = "'DataFrame' object has no attribute 'NONEXISTENT_NAME'" with pytest.raises(AttributeError, match=msg): float_frame.NONEXISTENT_NAME
def test_setattr_column(self): df = DataFrame({"foobar": 1}, index=range(10))
df.foobar = 5 assert (df.foobar == 5).all()
def test_setitem( self, float_frame, using_copy_on_write, warn_copy_on_write, using_infer_string ): # not sure what else to do here series = float_frame["A"][::2] float_frame["col5"] = series assert "col5" in float_frame
assert len(series) == 15 assert len(float_frame) == 30
exp = np.ravel(np.column_stack((series.values, [np.nan] * 15))) exp = Series(exp, index=float_frame.index, name="col5") tm.assert_series_equal(float_frame["col5"], exp)
series = float_frame["A"] float_frame["col6"] = series tm.assert_series_equal(series, float_frame["col6"], check_names=False)
# set ndarray arr = np.random.default_rng(2).standard_normal(len(float_frame)) float_frame["col9"] = arr assert (float_frame["col9"] == arr).all()
float_frame["col7"] = 5 assert (float_frame["col7"] == 5).all()
float_frame["col0"] = 3.14 assert (float_frame["col0"] == 3.14).all()
float_frame["col8"] = "foo" assert (float_frame["col8"] == "foo").all()
# this is partially a view (e.g. some blocks are view) # so raise/warn smaller = float_frame[:2]
msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame" if using_copy_on_write or warn_copy_on_write: # With CoW, adding a new column doesn't raise a warning smaller["col10"] = ["1", "2"] else: with pytest.raises(SettingWithCopyError, match=msg): smaller["col10"] = ["1", "2"]
if using_infer_string: assert smaller["col10"].dtype == "string" else: assert smaller["col10"].dtype == np.object_ assert (smaller["col10"] == ["1", "2"]).all()
def test_setitem2(self): # dtype changing GH4204 df = DataFrame([[0, 0]]) df.iloc[0] = np.nan expected = DataFrame([[np.nan, np.nan]]) tm.assert_frame_equal(df, expected)
df = DataFrame([[0, 0]]) df.loc[0] = np.nan tm.assert_frame_equal(df, expected)
def test_setitem_boolean(self, float_frame): df = float_frame.copy() values = float_frame.values.copy()
df[df["A"] > 0] = 4 values[values[:, 0] > 0] = 4 tm.assert_almost_equal(df.values, values)
# test that column reindexing works series = df["A"] == 4 series = series.reindex(df.index[::-1]) df[series] = 1 values[values[:, 0] == 4] = 1 tm.assert_almost_equal(df.values, values)
df[df > 0] = 5 values[values > 0] = 5 tm.assert_almost_equal(df.values, values)
df[df == 5] = 0 values[values == 5] = 0 tm.assert_almost_equal(df.values, values)
# a df that needs alignment first df[df[:-1] < 0] = 2 np.putmask(values[:-1], values[:-1] < 0, 2) tm.assert_almost_equal(df.values, values)
# indexed with same shape but rows-reversed df df[df[::-1] == 2] = 3 values[values == 2] = 3 tm.assert_almost_equal(df.values, values)
msg = "Must pass DataFrame or 2-d ndarray with boolean values only" with pytest.raises(TypeError, match=msg): df[df * 0] = 2
# index with DataFrame df_orig = df.copy() mask = df > np.abs(df) df[df > np.abs(df)] = np.nan values = df_orig.values.copy() values[mask.values] = np.nan expected = DataFrame(values, index=df_orig.index, columns=df_orig.columns) tm.assert_frame_equal(df, expected)
# set from DataFrame df[df > np.abs(df)] = df * 2 np.putmask(values, mask.values, df.values * 2) expected = DataFrame(values, index=df_orig.index, columns=df_orig.columns) tm.assert_frame_equal(df, expected)
def test_setitem_cast(self, float_frame): float_frame["D"] = float_frame["D"].astype("i8") assert float_frame["D"].dtype == np.int64
# #669, should not cast? # this is now set to int64, which means a replacement of the column to # the value dtype (and nothing to do with the existing dtype) float_frame["B"] = 0 assert float_frame["B"].dtype == np.int64
# cast if pass array of course float_frame["B"] = np.arange(len(float_frame)) assert issubclass(float_frame["B"].dtype.type, np.integer)
float_frame["foo"] = "bar" float_frame["foo"] = 0 assert float_frame["foo"].dtype == np.int64
float_frame["foo"] = "bar" float_frame["foo"] = 2.5 assert float_frame["foo"].dtype == np.float64
float_frame["something"] = 0 assert float_frame["something"].dtype == np.int64 float_frame["something"] = 2 assert float_frame["something"].dtype == np.int64 float_frame["something"] = 2.5 assert float_frame["something"].dtype == np.float64
def test_setitem_corner(self, float_frame, using_infer_string): # corner case df = DataFrame({"B": [1.0, 2.0, 3.0], "C": ["a", "b", "c"]}, index=np.arange(3)) del df["B"] df["B"] = [1.0, 2.0, 3.0] assert "B" in df assert len(df.columns) == 2
df["A"] = "beginning" df["E"] = "foo" df["D"] = "bar" df[datetime.now()] = "date" df[datetime.now()] = 5.0
# what to do when empty frame with index dm = DataFrame(index=float_frame.index) dm["A"] = "foo" dm["B"] = "bar" assert len(dm.columns) == 2 assert dm.values.dtype == np.object_
# upcast dm["C"] = 1 assert dm["C"].dtype == np.int64
dm["E"] = 1.0 assert dm["E"].dtype == np.float64
# set existing column dm["A"] = "bar" assert "bar" == dm["A"].iloc[0]
dm = DataFrame(index=np.arange(3)) dm["A"] = 1 dm["foo"] = "bar" del dm["foo"] dm["foo"] = "bar" if using_infer_string: assert dm["foo"].dtype == "string" else: assert dm["foo"].dtype == np.object_
dm["coercible"] = ["1", "2", "3"] if using_infer_string: assert dm["coercible"].dtype == "string" else: assert dm["coercible"].dtype == np.object_
def test_setitem_corner2(self): data = { "title": ["foobar", "bar", "foobar"] + ["foobar"] * 17, "cruft": np.random.default_rng(2).random(20), }
df = DataFrame(data) ix = df[df["title"] == "bar"].index
df.loc[ix, ["title"]] = "foobar" df.loc[ix, ["cruft"]] = 0
assert df.loc[1, "title"] == "foobar" assert df.loc[1, "cruft"] == 0
def test_setitem_ambig(self, using_infer_string): # Difficulties with mixed-type data # Created as float type dm = DataFrame(index=range(3), columns=range(3))
coercable_series = Series([Decimal(1) for _ in range(3)], index=range(3)) uncoercable_series = Series(["foo", "bzr", "baz"], index=range(3))
dm[0] = np.ones(3) assert len(dm.columns) == 3
dm[1] = coercable_series assert len(dm.columns) == 3
dm[2] = uncoercable_series assert len(dm.columns) == 3 if using_infer_string: assert dm[2].dtype == "string" else: assert dm[2].dtype == np.object_
def test_setitem_None(self, float_frame, using_infer_string): # GH #766 float_frame[None] = float_frame["A"] key = None if not using_infer_string else np.nan tm.assert_series_equal( float_frame.iloc[:, -1], float_frame["A"], check_names=False ) tm.assert_series_equal( float_frame.loc[:, key], float_frame["A"], check_names=False ) tm.assert_series_equal(float_frame[key], float_frame["A"], check_names=False)
def test_loc_setitem_boolean_mask_allfalse(self): # GH 9596 df = DataFrame( {"a": ["1", "2", "3"], "b": ["11", "22", "33"], "c": ["111", "222", "333"]} )
result = df.copy() result.loc[result.b.isna(), "a"] = result.a.copy() tm.assert_frame_equal(result, df)
def test_getitem_fancy_slice_integers_step(self): df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
# this is OK df.iloc[:8:2] df.iloc[:8:2] = np.nan assert isna(df.iloc[:8:2]).values.all()
def test_getitem_setitem_integer_slice_keyerrors(self): df = DataFrame( np.random.default_rng(2).standard_normal((10, 5)), index=range(0, 20, 2) )
# this is OK cp = df.copy() cp.iloc[4:10] = 0 assert (cp.iloc[4:10] == 0).values.all()
# so is this cp = df.copy() cp.iloc[3:11] = 0 assert (cp.iloc[3:11] == 0).values.all()
result = df.iloc[2:6] result2 = df.loc[3:11] expected = df.reindex([4, 6, 8, 10])
tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected)
# non-monotonic, raise KeyError df2 = df.iloc[list(range(5)) + list(range(5, 10))[::-1]] with pytest.raises(KeyError, match=r"^3$"): df2.loc[3:11] with pytest.raises(KeyError, match=r"^3$"): df2.loc[3:11] = 0
@td.skip_array_manager_invalid_test # already covered in test_iloc_col_slice_view def test_fancy_getitem_slice_mixed( self, float_frame, float_string_frame, using_copy_on_write, warn_copy_on_write ): sliced = float_string_frame.iloc[:, -3:] assert sliced["D"].dtype == np.float64
# get view with single block # setting it triggers setting with copy original = float_frame.copy() sliced = float_frame.iloc[:, -3:]
assert np.shares_memory(sliced["C"]._values, float_frame["C"]._values)
with tm.assert_cow_warning(warn_copy_on_write): sliced.loc[:, "C"] = 4.0 if not using_copy_on_write: assert (float_frame["C"] == 4).all()
# with the enforcement of GH#45333 in 2.0, this remains a view np.shares_memory(sliced["C"]._values, float_frame["C"]._values) else: tm.assert_frame_equal(float_frame, original)
def test_getitem_setitem_non_ix_labels(self): df = DataFrame(range(20), index=date_range("2020-01-01", periods=20))
start, end = df.index[[5, 10]]
result = df.loc[start:end] result2 = df[start:end] expected = df[5:11] tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected)
result = df.copy() result.loc[start:end] = 0 result2 = df.copy() result2[start:end] = 0 expected = df.copy() expected[5:11] = 0 tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected)
def test_ix_multi_take(self): df = DataFrame(np.random.default_rng(2).standard_normal((3, 2))) rs = df.loc[df.index == 0, :] xp = df.reindex([0]) tm.assert_frame_equal(rs, xp)
# GH#1321 df = DataFrame(np.random.default_rng(2).standard_normal((3, 2))) rs = df.loc[df.index == 0, df.columns == 1] xp = df.reindex(index=[0], columns=[1]) tm.assert_frame_equal(rs, xp)
def test_getitem_fancy_scalar(self, float_frame): f = float_frame ix = f.loc
# individual value for col in f.columns: ts = f[col] for idx in f.index[::5]: assert ix[idx, col] == ts[idx]
@td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values def test_setitem_fancy_scalar(self, float_frame): f = float_frame expected = float_frame.copy() ix = f.loc
# individual value for j, col in enumerate(f.columns): f[col] for idx in f.index[::5]: i = f.index.get_loc(idx) val = np.random.default_rng(2).standard_normal() expected.iloc[i, j] = val
ix[idx, col] = val tm.assert_frame_equal(f, expected)
def test_getitem_fancy_boolean(self, float_frame): f = float_frame ix = f.loc
expected = f.reindex(columns=["B", "D"]) result = ix[:, [False, True, False, True]] tm.assert_frame_equal(result, expected)
expected = f.reindex(index=f.index[5:10], columns=["B", "D"]) result = ix[f.index[5:10], [False, True, False, True]] tm.assert_frame_equal(result, expected)
boolvec = f.index > f.index[7] expected = f.reindex(index=f.index[boolvec]) result = ix[boolvec] tm.assert_frame_equal(result, expected) result = ix[boolvec, :] tm.assert_frame_equal(result, expected)
result = ix[boolvec, f.columns[2:]] expected = f.reindex(index=f.index[boolvec], columns=["C", "D"]) tm.assert_frame_equal(result, expected)
@td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values def test_setitem_fancy_boolean(self, float_frame): # from 2d, set with booleans frame = float_frame.copy() expected = float_frame.copy() values = expected.values.copy()
mask = frame["A"] > 0 frame.loc[mask] = 0.0 values[mask.values] = 0.0 expected = DataFrame(values, index=expected.index, columns=expected.columns) tm.assert_frame_equal(frame, expected)
frame = float_frame.copy() expected = float_frame.copy() values = expected.values.copy() frame.loc[mask, ["A", "B"]] = 0.0 values[mask.values, :2] = 0.0 expected = DataFrame(values, index=expected.index, columns=expected.columns) tm.assert_frame_equal(frame, expected)
def test_getitem_fancy_ints(self, float_frame): result = float_frame.iloc[[1, 4, 7]] expected = float_frame.loc[float_frame.index[[1, 4, 7]]] tm.assert_frame_equal(result, expected)
result = float_frame.iloc[:, [2, 0, 1]] expected = float_frame.loc[:, float_frame.columns[[2, 0, 1]]] tm.assert_frame_equal(result, expected)
def test_getitem_setitem_boolean_misaligned(self, float_frame): # boolean index misaligned labels mask = float_frame["A"][::-1] > 1
result = float_frame.loc[mask] expected = float_frame.loc[mask[::-1]] tm.assert_frame_equal(result, expected)
cp = float_frame.copy() expected = float_frame.copy() cp.loc[mask] = 0 expected.loc[mask] = 0 tm.assert_frame_equal(cp, expected)
def test_getitem_setitem_boolean_multi(self): df = DataFrame(np.random.default_rng(2).standard_normal((3, 2)))
# get k1 = np.array([True, False, True]) k2 = np.array([False, True]) result = df.loc[k1, k2] expected = df.loc[[0, 2], [1]] tm.assert_frame_equal(result, expected)
expected = df.copy() df.loc[np.array([True, False, True]), np.array([False, True])] = 5 expected.loc[[0, 2], [1]] = 5 tm.assert_frame_equal(df, expected)
def test_getitem_setitem_float_labels(self, using_array_manager): index = Index([1.5, 2, 3, 4, 5]) df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)), index=index)
result = df.loc[1.5:4] expected = df.reindex([1.5, 2, 3, 4]) tm.assert_frame_equal(result, expected) assert len(result) == 4
result = df.loc[4:5] expected = df.reindex([4, 5]) # reindex with int tm.assert_frame_equal(result, expected, check_index_type=False) assert len(result) == 2
result = df.loc[4:5] expected = df.reindex([4.0, 5.0]) # reindex with float tm.assert_frame_equal(result, expected) assert len(result) == 2
# loc_float changes this to work properly result = df.loc[1:2] expected = df.iloc[0:2] tm.assert_frame_equal(result, expected)
expected = df.iloc[0:2] msg = r"The behavior of obj\[i:j\] with a float-dtype index" with tm.assert_produces_warning(FutureWarning, match=msg): result = df[1:2] tm.assert_frame_equal(result, expected)
# #2727 index = Index([1.0, 2.5, 3.5, 4.5, 5.0]) df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)), index=index)
# positional slicing only via iloc! msg = ( "cannot do positional indexing on Index with " r"these indexers \[1.0\] of type float" ) with pytest.raises(TypeError, match=msg): df.iloc[1.0:5]
result = df.iloc[4:5] expected = df.reindex([5.0]) tm.assert_frame_equal(result, expected) assert len(result) == 1
cp = df.copy()
with pytest.raises(TypeError, match=_slice_msg): cp.iloc[1.0:5] = 0
with pytest.raises(TypeError, match=msg): result = cp.iloc[1.0:5] == 0
assert result.values.all() assert (cp.iloc[0:1] == df.iloc[0:1]).values.all()
cp = df.copy() cp.iloc[4:5] = 0 assert (cp.iloc[4:5] == 0).values.all() assert (cp.iloc[0:4] == df.iloc[0:4]).values.all()
# float slicing result = df.loc[1.0:5] expected = df tm.assert_frame_equal(result, expected) assert len(result) == 5
result = df.loc[1.1:5] expected = df.reindex([2.5, 3.5, 4.5, 5.0]) tm.assert_frame_equal(result, expected) assert len(result) == 4
result = df.loc[4.51:5] expected = df.reindex([5.0]) tm.assert_frame_equal(result, expected) assert len(result) == 1
result = df.loc[1.0:5.0] expected = df.reindex([1.0, 2.5, 3.5, 4.5, 5.0]) tm.assert_frame_equal(result, expected) assert len(result) == 5
cp = df.copy() cp.loc[1.0:5.0] = 0 result = cp.loc[1.0:5.0] assert (result == 0).values.all()
def test_setitem_single_column_mixed_datetime(self): df = DataFrame( np.random.default_rng(2).standard_normal((5, 3)), index=["a", "b", "c", "d", "e"], columns=["foo", "bar", "baz"], )
df["timestamp"] = Timestamp("20010102")
# check our dtypes result = df.dtypes expected = Series( [np.dtype("float64")] * 3 + [np.dtype("datetime64[s]")], index=["foo", "bar", "baz", "timestamp"], ) tm.assert_series_equal(result, expected)
# GH#16674 iNaT is treated as an integer when given by the user with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.loc["b", "timestamp"] = iNaT assert not isna(df.loc["b", "timestamp"]) assert df["timestamp"].dtype == np.object_ assert df.loc["b", "timestamp"] == iNaT
# allow this syntax (as of GH#3216) df.loc["c", "timestamp"] = np.nan assert isna(df.loc["c", "timestamp"])
# allow this syntax df.loc["d", :] = np.nan assert not isna(df.loc["c", :]).all()
def test_setitem_mixed_datetime(self): # GH 9336 expected = DataFrame( { "a": [0, 0, 0, 0, 13, 14], "b": [ datetime(2012, 1, 1), 1, "x", "y", datetime(2013, 1, 1), datetime(2014, 1, 1), ], } ) df = DataFrame(0, columns=list("ab"), index=range(6)) df["b"] = pd.NaT df.loc[0, "b"] = datetime(2012, 1, 1) with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.loc[1, "b"] = 1 df.loc[[2, 3], "b"] = "x", "y" A = np.array( [ [13, np.datetime64("2013-01-01T00:00:00")], [14, np.datetime64("2014-01-01T00:00:00")], ] ) df.loc[[4, 5], ["a", "b"]] = A tm.assert_frame_equal(df, expected)
def test_setitem_frame_float(self, float_frame): piece = float_frame.loc[float_frame.index[:2], ["A", "B"]] float_frame.loc[float_frame.index[-2] :, ["A", "B"]] = piece.values result = float_frame.loc[float_frame.index[-2:], ["A", "B"]].values expected = piece.values tm.assert_almost_equal(result, expected)
def test_setitem_frame_mixed(self, float_string_frame): # GH 3216
# already aligned f = float_string_frame.copy() piece = DataFrame( [[1.0, 2.0], [3.0, 4.0]], index=f.index[0:2], columns=["A", "B"] ) key = (f.index[slice(None, 2)], ["A", "B"]) f.loc[key] = piece tm.assert_almost_equal(f.loc[f.index[0:2], ["A", "B"]].values, piece.values)
def test_setitem_frame_mixed_rows_unaligned(self, float_string_frame): # GH#3216 rows unaligned f = float_string_frame.copy() piece = DataFrame( [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], index=list(f.index[0:2]) + ["foo", "bar"], columns=["A", "B"], ) key = (f.index[slice(None, 2)], ["A", "B"]) f.loc[key] = piece tm.assert_almost_equal( f.loc[f.index[0:2:], ["A", "B"]].values, piece.values[0:2] )
def test_setitem_frame_mixed_key_unaligned(self, float_string_frame): # GH#3216 key is unaligned with values f = float_string_frame.copy() piece = f.loc[f.index[:2], ["A"]] piece.index = f.index[-2:] key = (f.index[slice(-2, None)], ["A", "B"]) f.loc[key] = piece piece["B"] = np.nan tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values)
def test_setitem_frame_mixed_ndarray(self, float_string_frame): # GH#3216 ndarray f = float_string_frame.copy() piece = float_string_frame.loc[f.index[:2], ["A", "B"]] key = (f.index[slice(-2, None)], ["A", "B"]) f.loc[key] = piece.values tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values)
def test_setitem_frame_upcast(self): # needs upcasting df = DataFrame([[1, 2, "foo"], [3, 4, "bar"]], columns=["A", "B", "C"]) df2 = df.copy() with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): df2.loc[:, ["A", "B"]] = df.loc[:, ["A", "B"]] + 0.5 expected = df.reindex(columns=["A", "B"]) expected += 0.5 expected["C"] = df["C"] tm.assert_frame_equal(df2, expected)
def test_setitem_frame_align(self, float_frame): piece = float_frame.loc[float_frame.index[:2], ["A", "B"]] piece.index = float_frame.index[-2:] piece.columns = ["A", "B"] float_frame.loc[float_frame.index[-2:], ["A", "B"]] = piece result = float_frame.loc[float_frame.index[-2:], ["A", "B"]].values expected = piece.values tm.assert_almost_equal(result, expected)
def test_getitem_setitem_ix_duplicates(self): # #1201 df = DataFrame( np.random.default_rng(2).standard_normal((5, 3)), index=["foo", "foo", "bar", "baz", "bar"], )
result = df.loc["foo"] expected = df[:2] tm.assert_frame_equal(result, expected)
result = df.loc["bar"] expected = df.iloc[[2, 4]] tm.assert_frame_equal(result, expected)
result = df.loc["baz"] expected = df.iloc[3] tm.assert_series_equal(result, expected)
def test_getitem_ix_boolean_duplicates_multiple(self): # #1201 df = DataFrame( np.random.default_rng(2).standard_normal((5, 3)), index=["foo", "foo", "bar", "baz", "bar"], )
result = df.loc[["bar"]] exp = df.iloc[[2, 4]] tm.assert_frame_equal(result, exp)
result = df.loc[df[1] > 0] exp = df[df[1] > 0] tm.assert_frame_equal(result, exp)
result = df.loc[df[0] > 0] exp = df[df[0] > 0] tm.assert_frame_equal(result, exp)
@pytest.mark.parametrize("bool_value", [True, False]) def test_getitem_setitem_ix_bool_keyerror(self, bool_value): # #2199 df = DataFrame({"a": [1, 2, 3]}) message = f"{bool_value}: boolean label can not be used without a boolean index" with pytest.raises(KeyError, match=message): df.loc[bool_value]
msg = "cannot use a single bool to index into setitem" with pytest.raises(KeyError, match=msg): df.loc[bool_value] = 0
# TODO: rename? remove? def test_single_element_ix_dont_upcast(self, float_frame): float_frame["E"] = 1 assert issubclass(float_frame["E"].dtype.type, (int, np.integer))
result = float_frame.loc[float_frame.index[5], "E"] assert is_integer(result)
# GH 11617 df = DataFrame({"a": [1.23]}) df["b"] = 666
result = df.loc[0, "b"] assert is_integer(result)
expected = Series([666], [0], name="b") result = df.loc[[0], "b"] tm.assert_series_equal(result, expected)
def test_iloc_callable_tuple_return_value(self): # GH53769 df = DataFrame(np.arange(40).reshape(10, 4), index=range(0, 20, 2)) msg = "callable with iloc" with tm.assert_produces_warning(FutureWarning, match=msg): df.iloc[lambda _: (0,)] with tm.assert_produces_warning(FutureWarning, match=msg): df.iloc[lambda _: (0,)] = 1
def test_iloc_row(self): df = DataFrame( np.random.default_rng(2).standard_normal((10, 4)), index=range(0, 20, 2) )
result = df.iloc[1] exp = df.loc[2] tm.assert_series_equal(result, exp)
result = df.iloc[2] exp = df.loc[4] tm.assert_series_equal(result, exp)
# slice result = df.iloc[slice(4, 8)] expected = df.loc[8:14] tm.assert_frame_equal(result, expected)
# list of integers result = df.iloc[[1, 2, 4, 6]] expected = df.reindex(df.index[[1, 2, 4, 6]]) tm.assert_frame_equal(result, expected)
def test_iloc_row_slice_view(self, using_copy_on_write, warn_copy_on_write): df = DataFrame( np.random.default_rng(2).standard_normal((10, 4)), index=range(0, 20, 2) ) original = df.copy()
# verify slice is view # setting it makes it raise/warn subset = df.iloc[slice(4, 8)]
assert np.shares_memory(df[2], subset[2])
exp_col = original[2].copy() with tm.assert_cow_warning(warn_copy_on_write): subset.loc[:, 2] = 0.0 if not using_copy_on_write: exp_col._values[4:8] = 0.0
# With the enforcement of GH#45333 in 2.0, this remains a view assert np.shares_memory(df[2], subset[2]) tm.assert_series_equal(df[2], exp_col)
def test_iloc_col(self): df = DataFrame( np.random.default_rng(2).standard_normal((4, 10)), columns=range(0, 20, 2) )
result = df.iloc[:, 1] exp = df.loc[:, 2] tm.assert_series_equal(result, exp)
result = df.iloc[:, 2] exp = df.loc[:, 4] tm.assert_series_equal(result, exp)
# slice result = df.iloc[:, slice(4, 8)] expected = df.loc[:, 8:14] tm.assert_frame_equal(result, expected)
# list of integers result = df.iloc[:, [1, 2, 4, 6]] expected = df.reindex(columns=df.columns[[1, 2, 4, 6]]) tm.assert_frame_equal(result, expected)
def test_iloc_col_slice_view( self, using_array_manager, using_copy_on_write, warn_copy_on_write ): df = DataFrame( np.random.default_rng(2).standard_normal((4, 10)), columns=range(0, 20, 2) ) original = df.copy() subset = df.iloc[:, slice(4, 8)]
if not using_array_manager and not using_copy_on_write: # verify slice is view assert np.shares_memory(df[8]._values, subset[8]._values)
with tm.assert_cow_warning(warn_copy_on_write): subset.loc[:, 8] = 0.0
assert (df[8] == 0).all()
# with the enforcement of GH#45333 in 2.0, this remains a view assert np.shares_memory(df[8]._values, subset[8]._values) else: if using_copy_on_write: # verify slice is view assert np.shares_memory(df[8]._values, subset[8]._values) subset[8] = 0.0 # subset changed assert (subset[8] == 0).all() # but df itself did not change (setitem replaces full column) tm.assert_frame_equal(df, original)
def test_loc_duplicates(self): # gh-17105
# insert a duplicate element to the index trange = date_range( start=Timestamp(year=2017, month=1, day=1), end=Timestamp(year=2017, month=1, day=5), )
trange = trange.insert(loc=5, item=Timestamp(year=2017, month=1, day=5))
df = DataFrame(0, index=trange, columns=["A", "B"]) bool_idx = np.array([False, False, False, False, False, True])
# assignment df.loc[trange[bool_idx], "A"] = 6
expected = DataFrame( {"A": [0, 0, 0, 0, 6, 6], "B": [0, 0, 0, 0, 0, 0]}, index=trange ) tm.assert_frame_equal(df, expected)
# in-place df = DataFrame(0, index=trange, columns=["A", "B"]) df.loc[trange[bool_idx], "A"] += 6 tm.assert_frame_equal(df, expected)
def test_setitem_with_unaligned_tz_aware_datetime_column(self): # GH 12981 # Assignment of unaligned offset-aware datetime series. # Make sure timezone isn't lost column = Series(date_range("2015-01-01", periods=3, tz="utc"), name="dates") df = DataFrame({"dates": column}) df["dates"] = column[[1, 0, 2]] tm.assert_series_equal(df["dates"], column)
df = DataFrame({"dates": column}) df.loc[[0, 1, 2], "dates"] = column[[1, 0, 2]] tm.assert_series_equal(df["dates"], column)
def test_loc_setitem_datetimelike_with_inference(self): # GH 7592 # assignment of timedeltas with NaT
one_hour = timedelta(hours=1) df = DataFrame(index=date_range("20130101", periods=4)) df["A"] = np.array([1 * one_hour] * 4, dtype="m8[ns]") df.loc[:, "B"] = np.array([2 * one_hour] * 4, dtype="m8[ns]") df.loc[df.index[:3], "C"] = np.array([3 * one_hour] * 3, dtype="m8[ns]") df.loc[:, "D"] = np.array([4 * one_hour] * 4, dtype="m8[ns]") df.loc[df.index[:3], "E"] = np.array([5 * one_hour] * 3, dtype="m8[ns]") df["F"] = np.timedelta64("NaT") df.loc[df.index[:-1], "F"] = np.array([6 * one_hour] * 3, dtype="m8[ns]") df.loc[df.index[-3] :, "G"] = date_range("20130101", periods=3) df["H"] = np.datetime64("NaT") result = df.dtypes expected = Series( [np.dtype("timedelta64[ns]")] * 6 + [np.dtype("datetime64[ns]")] * 2, index=list("ABCDEFGH"), ) tm.assert_series_equal(result, expected)
def test_getitem_boolean_indexing_mixed(self): df = DataFrame( { 0: {35: np.nan, 40: np.nan, 43: np.nan, 49: np.nan, 50: np.nan}, 1: { 35: np.nan, 40: 0.32632316859446198, 43: np.nan, 49: 0.32632316859446198, 50: 0.39114724480578139, }, 2: { 35: np.nan, 40: np.nan, 43: 0.29012581014105987, 49: np.nan, 50: np.nan, }, 3: {35: np.nan, 40: np.nan, 43: np.nan, 49: np.nan, 50: np.nan}, 4: { 35: 0.34215328467153283, 40: np.nan, 43: np.nan, 49: np.nan, 50: np.nan, }, "y": {35: 0, 40: 0, 43: 0, 49: 0, 50: 1}, } )
# mixed int/float ok df2 = df.copy() df2[df2 > 0.3] = 1 expected = df.copy() expected.loc[40, 1] = 1 expected.loc[49, 1] = 1 expected.loc[50, 1] = 1 expected.loc[35, 4] = 1 tm.assert_frame_equal(df2, expected)
df["foo"] = "test" msg = "not supported between instances|unorderable types"
with pytest.raises(TypeError, match=msg): df[df > 0.3] = 1
def test_type_error_multiindex(self): # See gh-12218 mi = MultiIndex.from_product([["x", "y"], [0, 1]], names=[None, "c"]) dg = DataFrame( [[1, 1, 2, 2], [3, 3, 4, 4]], columns=mi, index=Index([0, 1], name="i") ) with pytest.raises(InvalidIndexError, match="slice"): dg[:, 0]
index = Index(range(2), name="i") columns = MultiIndex( levels=[["x", "y"], [0, 1]], codes=[[0, 1], [0, 0]], names=[None, "c"] ) expected = DataFrame([[1, 2], [3, 4]], columns=columns, index=index)
result = dg.loc[:, (slice(None), 0)] tm.assert_frame_equal(result, expected)
name = ("x", 0) index = Index(range(2), name="i") expected = Series([1, 3], index=index, name=name)
result = dg["x", 0] tm.assert_series_equal(result, expected)
def test_getitem_interval_index_partial_indexing(self): # GH#36490 df = DataFrame( np.ones((3, 4)), columns=pd.IntervalIndex.from_breaks(np.arange(5)) )
expected = df.iloc[:, 0]
res = df[0.5] tm.assert_series_equal(res, expected)
res = df.loc[:, 0.5] tm.assert_series_equal(res, expected)
def test_setitem_array_as_cell_value(self): # GH#43422 df = DataFrame(columns=["a", "b"], dtype=object) df.loc[0] = {"a": np.zeros((2,)), "b": np.zeros((2, 2))} expected = DataFrame({"a": [np.zeros((2,))], "b": [np.zeros((2, 2))]}) tm.assert_frame_equal(df, expected)
def test_iloc_setitem_nullable_2d_values(self): df = DataFrame({"A": [1, 2, 3]}, dtype="Int64") orig = df.copy()
df.loc[:] = df.values[:, ::-1] tm.assert_frame_equal(df, orig)
df.loc[:] = pd.core.arrays.NumpyExtensionArray(df.values[:, ::-1]) tm.assert_frame_equal(df, orig)
df.iloc[:] = df.iloc[:, :].copy() tm.assert_frame_equal(df, orig)
def test_getitem_segfault_with_empty_like_object(self): # GH#46848 df = DataFrame(np.empty((1, 1), dtype=object)) df[0] = np.empty_like(df[0]) # this produces the segfault df[[0]]
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") @pytest.mark.parametrize( "null", [pd.NaT, pd.NaT.to_numpy("M8[ns]"), pd.NaT.to_numpy("m8[ns]")] ) def test_setting_mismatched_na_into_nullable_fails( self, null, any_numeric_ea_dtype ): # GH#44514 don't cast mismatched nulls to pd.NA df = DataFrame({"A": [1, 2, 3]}, dtype=any_numeric_ea_dtype) ser = df["A"].copy() arr = ser._values
msg = "|".join( [ r"timedelta64\[ns\] cannot be converted to (Floating|Integer)Dtype", r"datetime64\[ns\] cannot be converted to (Floating|Integer)Dtype", "'values' contains non-numeric NA", r"Invalid value '.*' for dtype (U?Int|Float)\d{1,2}", ] ) with pytest.raises(TypeError, match=msg): arr[0] = null
with pytest.raises(TypeError, match=msg): arr[:2] = [null, null]
with pytest.raises(TypeError, match=msg): ser[0] = null
with pytest.raises(TypeError, match=msg): ser[:2] = [null, null]
with pytest.raises(TypeError, match=msg): ser.iloc[0] = null
with pytest.raises(TypeError, match=msg): ser.iloc[:2] = [null, null]
with pytest.raises(TypeError, match=msg): df.iloc[0, 0] = null
with pytest.raises(TypeError, match=msg): df.iloc[:2, 0] = [null, null]
# Multi-Block df2 = df.copy() df2["B"] = ser.copy() with pytest.raises(TypeError, match=msg): df2.iloc[0, 0] = null
with pytest.raises(TypeError, match=msg): df2.iloc[:2, 0] = [null, null]
def test_loc_expand_empty_frame_keep_index_name(self): # GH#45621 df = DataFrame(columns=["b"], index=Index([], name="a")) df.loc[0] = 1 expected = DataFrame({"b": [1]}, index=Index([0], name="a")) tm.assert_frame_equal(df, expected)
def test_loc_expand_empty_frame_keep_midx_names(self): # GH#46317 df = DataFrame( columns=["d"], index=MultiIndex.from_tuples([], names=["a", "b", "c"]) ) df.loc[(1, 2, 3)] = "foo" expected = DataFrame( {"d": ["foo"]}, index=MultiIndex.from_tuples([(1, 2, 3)], names=["a", "b", "c"]), ) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( "val, idxr", [ ("x", "a"), ("x", ["a"]), (1, "a"), (1, ["a"]), ], ) def test_loc_setitem_rhs_frame(self, idxr, val): # GH#47578 df = DataFrame({"a": [1, 2]})
with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.loc[:, idxr] = DataFrame({"a": [val, 11]}, index=[1, 2]) expected = DataFrame({"a": [np.nan, val]}) tm.assert_frame_equal(df, expected)
@td.skip_array_manager_invalid_test def test_iloc_setitem_enlarge_no_warning(self, warn_copy_on_write): # GH#47381 df = DataFrame(columns=["a", "b"]) expected = df.copy() view = df[:] df.iloc[:, 0] = np.array([1, 2], dtype=np.float64) tm.assert_frame_equal(view, expected)
def test_loc_internals_not_updated_correctly(self): # GH#47867 all steps are necessary to reproduce the initial bug df = DataFrame( {"bool_col": True, "a": 1, "b": 2.5}, index=MultiIndex.from_arrays([[1, 2], [1, 2]], names=["idx1", "idx2"]), ) idx = [(1, 1)]
df["c"] = 3 df.loc[idx, "c"] = 0
df.loc[idx, "c"] df.loc[idx, ["a", "b"]]
df.loc[idx, "c"] = 15 result = df.loc[idx, "c"] expected = df = Series( 15, index=MultiIndex.from_arrays([[1], [1]], names=["idx1", "idx2"]), name="c", ) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("val", [None, [None], pd.NA, [pd.NA]]) def test_iloc_setitem_string_list_na(self, val): # GH#45469 df = DataFrame({"a": ["a", "b", "c"]}, dtype="string") df.iloc[[0], :] = val expected = DataFrame({"a": [pd.NA, "b", "c"]}, dtype="string") tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("val", [None, pd.NA]) def test_iloc_setitem_string_na(self, val): # GH#45469 df = DataFrame({"a": ["a", "b", "c"]}, dtype="string") df.iloc[0, :] = val expected = DataFrame({"a": [pd.NA, "b", "c"]}, dtype="string") tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("func", [list, Series, np.array]) def test_iloc_setitem_ea_null_slice_length_one_list(self, func): # GH#48016 df = DataFrame({"a": [1, 2, 3]}, dtype="Int64") df.iloc[:, func([0])] = 5 expected = DataFrame({"a": [5, 5, 5]}, dtype="Int64") tm.assert_frame_equal(df, expected)
def test_loc_named_tuple_for_midx(self): # GH#48124 df = DataFrame( index=MultiIndex.from_product( [["A", "B"], ["a", "b", "c"]], names=["first", "second"] ) ) indexer_tuple = namedtuple("Indexer", df.index.names) idxr = indexer_tuple(first="A", second=["a", "b"]) result = df.loc[idxr, :] expected = DataFrame( index=MultiIndex.from_tuples( [("A", "a"), ("A", "b")], names=["first", "second"] ) ) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("indexer", [["a"], "a"]) @pytest.mark.parametrize("col", [{}, {"b": 1}]) def test_set_2d_casting_date_to_int(self, col, indexer): # GH#49159 df = DataFrame( {"a": [Timestamp("2022-12-29"), Timestamp("2022-12-30")], **col}, ) df.loc[[1], indexer] = df["a"] + pd.Timedelta(days=1) expected = DataFrame( {"a": [Timestamp("2022-12-29"), Timestamp("2022-12-31")], **col}, ) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("col", [{}, {"name": "a"}]) def test_loc_setitem_reordering_with_all_true_indexer(self, col): # GH#48701 n = 17 df = DataFrame({**col, "x": range(n), "y": range(n)}) expected = df.copy() df.loc[n * [True], ["x", "y"]] = df[["x", "y"]] tm.assert_frame_equal(df, expected)
def test_loc_rhs_empty_warning(self): # GH48480 df = DataFrame(columns=["a", "b"]) expected = df.copy() rhs = DataFrame(columns=["a"]) with tm.assert_produces_warning(None): df.loc[:, "a"] = rhs tm.assert_frame_equal(df, expected)
def test_iloc_ea_series_indexer(self): # GH#49521 df = DataFrame([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) indexer = Series([0, 1], dtype="Int64") row_indexer = Series([1], dtype="Int64") result = df.iloc[row_indexer, indexer] expected = DataFrame([[5, 6]], index=[1]) tm.assert_frame_equal(result, expected)
result = df.iloc[row_indexer.values, indexer.values] tm.assert_frame_equal(result, expected)
def test_iloc_ea_series_indexer_with_na(self): # GH#49521 df = DataFrame([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) indexer = Series([0, pd.NA], dtype="Int64") msg = "cannot convert" with pytest.raises(ValueError, match=msg): df.iloc[:, indexer] with pytest.raises(ValueError, match=msg): df.iloc[:, indexer.values]
@pytest.mark.parametrize("indexer", [True, (True,)]) @pytest.mark.parametrize("dtype", [bool, "boolean"]) def test_loc_bool_multiindex(self, dtype, indexer): # GH#47687 midx = MultiIndex.from_arrays( [ Series([True, True, False, False], dtype=dtype), Series([True, False, True, False], dtype=dtype), ], names=["a", "b"], ) df = DataFrame({"c": [1, 2, 3, 4]}, index=midx) with tm.maybe_produces_warning(PerformanceWarning, isinstance(indexer, tuple)): result = df.loc[indexer] expected = DataFrame( {"c": [1, 2]}, index=Index([True, False], name="b", dtype=dtype) ) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("utc", [False, True]) @pytest.mark.parametrize("indexer", ["date", ["date"]]) def test_loc_datetime_assignment_dtype_does_not_change(self, utc, indexer): # GH#49837 df = DataFrame( { "date": to_datetime( [datetime(2022, 1, 20), datetime(2022, 1, 22)], utc=utc ), "update": [True, False], } ) expected = df.copy(deep=True)
update_df = df[df["update"]]
df.loc[df["update"], indexer] = update_df["date"]
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("indexer, idx", [(tm.loc, 1), (tm.iloc, 2)]) def test_setitem_value_coercing_dtypes(self, indexer, idx): # GH#50467 df = DataFrame([["1", np.nan], ["2", np.nan], ["3", np.nan]], dtype=object) rhs = DataFrame([[1, np.nan], [2, np.nan]]) indexer(df)[:idx, :] = rhs expected = DataFrame([[1, np.nan], [2, np.nan], ["3", np.nan]], dtype=object) tm.assert_frame_equal(df, expected)
class TestDataFrameIndexingUInt64: def test_setitem(self): df = DataFrame( {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64, ) idx = df["A"].rename("foo")
# setitem assert "C" not in df.columns df["C"] = idx tm.assert_series_equal(df["C"], Series(idx, name="C"))
assert "D" not in df.columns df["D"] = "foo" df["D"] = idx tm.assert_series_equal(df["D"], Series(idx, name="D")) del df["D"]
# With NaN: because uint64 has no NaN element, # the column should be cast to object. df2 = df.copy() with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): df2.iloc[1, 1] = pd.NaT df2.iloc[1, 2] = pd.NaT result = df2["B"] tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) tm.assert_series_equal( df2.dtypes, Series( [np.dtype("uint64"), np.dtype("O"), np.dtype("O")], index=["A", "B", "C"], ), )
def test_object_casting_indexing_wraps_datetimelike(using_array_manager): # GH#31649, check the indexing methods all the way down the stack df = DataFrame( { "A": [1, 2], "B": date_range("2000", periods=2), "C": pd.timedelta_range("1 Day", periods=2), } )
ser = df.loc[0] assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta)
ser = df.iloc[0] assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta)
ser = df.xs(0, axis=0) assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta)
if using_array_manager: # remainder of the test checking BlockManager internals return
mgr = df._mgr mgr._rebuild_blknos_and_blklocs() arr = mgr.fast_xs(0).array assert isinstance(arr[1], Timestamp) assert isinstance(arr[2], pd.Timedelta)
blk = mgr.blocks[mgr.blknos[1]] assert blk.dtype == "M8[ns]" # we got the right block val = blk.iget((0, 0)) assert isinstance(val, Timestamp)
blk = mgr.blocks[mgr.blknos[2]] assert blk.dtype == "m8[ns]" # we got the right block val = blk.iget((0, 0)) assert isinstance(val, pd.Timedelta)
msg1 = r"Cannot setitem on a Categorical with a new category( \(.*\))?, set the"msg2 = "Cannot set a Categorical with another, without identical categories"
class TestLocILocDataFrameCategorical: @pytest.fixture def orig(self): cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) idx = Index(["h", "i", "j", "k", "l", "m", "n"]) values = [1, 1, 1, 1, 1, 1, 1] orig = DataFrame({"cats": cats, "values": values}, index=idx) return orig
@pytest.fixture def exp_single_row(self): # The expected values if we change a single row cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) values1 = [1, 1, 2, 1, 1, 1, 1] exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1) return exp_single_row
@pytest.fixture def exp_multi_row(self): # assign multiple rows (mixed values) (-> array) -> exp_multi_row # changed multiple rows cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) values2 = [1, 1, 2, 2, 1, 1, 1] exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) return exp_multi_row
@pytest.fixture def exp_parts_cats_col(self): # changed part of the cats column cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) values3 = [1, 1, 1, 1, 1, 1, 1] exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3) return exp_parts_cats_col
@pytest.fixture def exp_single_cats_value(self): # changed single value in cats col cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) values4 = [1, 1, 1, 1, 1, 1, 1] exp_single_cats_value = DataFrame( {"cats": cats4, "values": values4}, index=idx4 ) return exp_single_cats_value
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer): # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy()
key = slice(2, 4) if indexer is tm.loc: key = slice("j", "k")
indexer(df)[key, :] = [["b", 2], ["b", 2]] tm.assert_frame_equal(df, exp_multi_row)
df = orig.copy() with pytest.raises(TypeError, match=msg1): indexer(df)[key, :] = [["c", 2], ["c", 2]]
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc, tm.at, tm.iat]) def test_loc_iloc_at_iat_setitem_single_value_in_categories( self, orig, exp_single_cats_value, indexer ): # - assign a single value -> exp_single_cats_value df = orig.copy()
key = (2, 0) if indexer in [tm.loc, tm.at]: key = (df.index[2], df.columns[0])
# "b" is among the categories for df["cat"}] indexer(df)[key] = "b" tm.assert_frame_equal(df, exp_single_cats_value)
# "c" is not among the categories for df["cat"] with pytest.raises(TypeError, match=msg1): indexer(df)[key] = "c"
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) def test_loc_iloc_setitem_mask_single_value_in_categories( self, orig, exp_single_cats_value, indexer ): # mask with single True df = orig.copy()
mask = df.index == "j" key = 0 if indexer is tm.loc: key = df.columns[key]
indexer(df)[mask, key] = "b" tm.assert_frame_equal(df, exp_single_cats_value)
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) def test_loc_iloc_setitem_full_row_non_categorical_rhs( self, orig, exp_single_row, indexer ): # - assign a complete row (mixed values) -> exp_single_row df = orig.copy()
key = 2 if indexer is tm.loc: key = df.index[2]
# not categorical dtype, but "b" _is_ among the categories for df["cat"] indexer(df)[key, :] = ["b", 2] tm.assert_frame_equal(df, exp_single_row)
# "c" is not among the categories for df["cat"] with pytest.raises(TypeError, match=msg1): indexer(df)[key, :] = ["c", 2]
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) def test_loc_iloc_setitem_partial_col_categorical_rhs( self, orig, exp_parts_cats_col, indexer ): # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy()
key = (slice(2, 4), 0) if indexer is tm.loc: key = (slice("j", "k"), df.columns[0])
# same categories as we currently have in df["cats"] compat = Categorical(["b", "b"], categories=["a", "b"]) indexer(df)[key] = compat tm.assert_frame_equal(df, exp_parts_cats_col)
# categories do not match df["cat"]'s, but "b" is among them semi_compat = Categorical(list("bb"), categories=list("abc")) with pytest.raises(TypeError, match=msg2): # different categories but holdable values # -> not sure if this should fail or pass indexer(df)[key] = semi_compat
# categories do not match df["cat"]'s, and "c" is not among them incompat = Categorical(list("cc"), categories=list("abc")) with pytest.raises(TypeError, match=msg2): # different values indexer(df)[key] = incompat
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) def test_loc_iloc_setitem_non_categorical_rhs( self, orig, exp_parts_cats_col, indexer ): # assign a part of a column with dtype != categorical -> exp_parts_cats_col df = orig.copy()
key = (slice(2, 4), 0) if indexer is tm.loc: key = (slice("j", "k"), df.columns[0])
# "b" is among the categories for df["cat"] indexer(df)[key] = ["b", "b"] tm.assert_frame_equal(df, exp_parts_cats_col)
# "c" not part of the categories with pytest.raises(TypeError, match=msg1): indexer(df)[key] = ["c", "c"]
@pytest.mark.parametrize("indexer", [tm.getitem, tm.loc, tm.iloc]) def test_getitem_preserve_object_index_with_dates(self, indexer): # https://github.com/pandas-dev/pandas/pull/42950 - when selecting a column # from dataframe, don't try to infer object dtype index on Series construction idx = date_range("2012", periods=3).astype(object) df = DataFrame({0: [1, 2, 3]}, index=idx) assert df.index.dtype == object
if indexer is tm.getitem: ser = indexer(df)[0] else: ser = indexer(df)[:, 0]
assert ser.index.dtype == object
def test_loc_on_multiindex_one_level(self): # GH#45779 df = DataFrame( data=[[0], [1]], index=MultiIndex.from_tuples([("a",), ("b",)], names=["first"]), ) expected = DataFrame( data=[[0]], index=MultiIndex.from_tuples([("a",)], names=["first"]) ) result = df.loc["a"] tm.assert_frame_equal(result, expected)
class TestDeprecatedIndexers: @pytest.mark.parametrize( "key", [{1}, {1: 1}, ({1}, "a"), ({1: 1}, "a"), (1, {"a"}), (1, {"a": "a"})] ) def test_getitem_dict_and_set_deprecated(self, key): # GH#42825 enforced in 2.0 df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) with pytest.raises(TypeError, match="as an indexer is not supported"): df.loc[key]
@pytest.mark.parametrize( "key", [ {1}, {1: 1}, (({1}, 2), "a"), (({1: 1}, 2), "a"), ((1, 2), {"a"}), ((1, 2), {"a": "a"}), ], ) def test_getitem_dict_and_set_deprecated_multiindex(self, key): # GH#42825 enforced in 2.0 df = DataFrame( [[1, 2], [3, 4]], columns=["a", "b"], index=MultiIndex.from_tuples([(1, 2), (3, 4)]), ) with pytest.raises(TypeError, match="as an indexer is not supported"): df.loc[key]
@pytest.mark.parametrize( "key", [{1}, {1: 1}, ({1}, "a"), ({1: 1}, "a"), (1, {"a"}), (1, {"a": "a"})] ) def test_setitem_dict_and_set_disallowed(self, key): # GH#42825 enforced in 2.0 df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) with pytest.raises(TypeError, match="as an indexer is not supported"): df.loc[key] = 1
@pytest.mark.parametrize( "key", [ {1}, {1: 1}, (({1}, 2), "a"), (({1: 1}, 2), "a"), ((1, 2), {"a"}), ((1, 2), {"a": "a"}), ], ) def test_setitem_dict_and_set_disallowed_multiindex(self, key): # GH#42825 enforced in 2.0 df = DataFrame( [[1, 2], [3, 4]], columns=["a", "b"], index=MultiIndex.from_tuples([(1, 2), (3, 4)]), ) with pytest.raises(TypeError, match="as an indexer is not supported"): df.loc[key] = 1
def test_adding_new_conditional_column() -> None: # https://github.com/pandas-dev/pandas/issues/55025 df = DataFrame({"x": [1]}) df.loc[df["x"] == 1, "y"] = "1" expected = DataFrame({"x": [1], "y": ["1"]}) tm.assert_frame_equal(df, expected)
df = DataFrame({"x": [1]}) # try inserting something which numpy would store as 'object' value = lambda x: x df.loc[df["x"] == 1, "y"] = value expected = DataFrame({"x": [1], "y": [value]}) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( ("dtype", "infer_string"), [ (object, False), ("string[pyarrow_numpy]", True), ],)def test_adding_new_conditional_column_with_string(dtype, infer_string) -> None: # https://github.com/pandas-dev/pandas/issues/56204 pytest.importorskip("pyarrow")
df = DataFrame({"a": [1, 2], "b": [3, 4]}) with pd.option_context("future.infer_string", infer_string): df.loc[df["a"] == 1, "c"] = "1" expected = DataFrame({"a": [1, 2], "b": [3, 4], "c": ["1", float("nan")]}).astype( {"a": "int64", "b": "int64", "c": dtype} ) tm.assert_frame_equal(df, expected)
def test_add_new_column_infer_string(): # GH#55366 pytest.importorskip("pyarrow") df = DataFrame({"x": [1]}) with pd.option_context("future.infer_string", True): df.loc[df["x"] == 1, "y"] = "1" expected = DataFrame( {"x": [1], "y": Series(["1"], dtype="string[pyarrow_numpy]")}, columns=Index(["x", "y"], dtype=object), ) tm.assert_frame_equal(df, expected)
class TestSetitemValidation: # This is adapted from pandas/tests/arrays/masked/test_indexing.py # but checks for warnings instead of errors. def _check_setitem_invalid(self, df, invalid, indexer, warn): msg = "Setting an item of incompatible dtype is deprecated" msg = re.escape(msg)
orig_df = df.copy()
# iloc with tm.assert_produces_warning(warn, match=msg): df.iloc[indexer, 0] = invalid df = orig_df.copy()
# loc with tm.assert_produces_warning(warn, match=msg): df.loc[indexer, "a"] = invalid df = orig_df.copy()
_invalid_scalars = [ 1 + 2j, "True", "1", "1.0", pd.NaT, np.datetime64("NaT"), np.timedelta64("NaT"), ] _indexers = [0, [0], slice(0, 1), [True, False, False], slice(None, None, None)]
@pytest.mark.parametrize( "invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)] ) @pytest.mark.parametrize("indexer", _indexers) def test_setitem_validation_scalar_bool(self, invalid, indexer): df = DataFrame({"a": [True, False, False]}, dtype="bool") self._check_setitem_invalid(df, invalid, indexer, FutureWarning)
@pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)]) @pytest.mark.parametrize("indexer", _indexers) def test_setitem_validation_scalar_int(self, invalid, any_int_numpy_dtype, indexer): df = DataFrame({"a": [1, 2, 3]}, dtype=any_int_numpy_dtype) if isna(invalid) and invalid is not pd.NaT and not np.isnat(invalid): warn = None else: warn = FutureWarning self._check_setitem_invalid(df, invalid, indexer, warn)
@pytest.mark.parametrize("invalid", _invalid_scalars + [True]) @pytest.mark.parametrize("indexer", _indexers) def test_setitem_validation_scalar_float(self, invalid, float_numpy_dtype, indexer): df = DataFrame({"a": [1, 2, None]}, dtype=float_numpy_dtype) self._check_setitem_invalid(df, invalid, indexer, FutureWarning)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""test_insert is specifically for the DataFrame.insert method; not to beconfused with tests with "insert" in their names that are really testing__setitem__."""import numpy as npimport pytest
from pandas.errors import PerformanceWarning
from pandas import ( DataFrame, Index,)import pandas._testing as tm
class TestDataFrameInsert: def test_insert(self): df = DataFrame( np.random.default_rng(2).standard_normal((5, 3)), index=np.arange(5), columns=["c", "b", "a"], )
df.insert(0, "foo", df["a"]) tm.assert_index_equal(df.columns, Index(["foo", "c", "b", "a"])) tm.assert_series_equal(df["a"], df["foo"], check_names=False)
df.insert(2, "bar", df["c"]) tm.assert_index_equal(df.columns, Index(["foo", "c", "bar", "b", "a"])) tm.assert_almost_equal(df["c"], df["bar"], check_names=False)
with pytest.raises(ValueError, match="already exists"): df.insert(1, "a", df["b"])
msg = "cannot insert c, already exists" with pytest.raises(ValueError, match=msg): df.insert(1, "c", df["b"])
df.columns.name = "some_name" # preserve columns name field df.insert(0, "baz", df["c"]) assert df.columns.name == "some_name"
def test_insert_column_bug_4032(self): # GH#4032, inserting a column and renaming causing errors df = DataFrame({"b": [1.1, 2.2]})
df = df.rename(columns={}) df.insert(0, "a", [1, 2]) result = df.rename(columns={})
expected = DataFrame([[1, 1.1], [2, 2.2]], columns=["a", "b"]) tm.assert_frame_equal(result, expected)
df.insert(0, "c", [1.3, 2.3]) result = df.rename(columns={})
expected = DataFrame([[1.3, 1, 1.1], [2.3, 2, 2.2]], columns=["c", "a", "b"]) tm.assert_frame_equal(result, expected)
def test_insert_with_columns_dups(self): # GH#14291 df = DataFrame() df.insert(0, "A", ["g", "h", "i"], allow_duplicates=True) df.insert(0, "A", ["d", "e", "f"], allow_duplicates=True) df.insert(0, "A", ["a", "b", "c"], allow_duplicates=True) exp = DataFrame( [["a", "d", "g"], ["b", "e", "h"], ["c", "f", "i"]], columns=["A", "A", "A"] ) tm.assert_frame_equal(df, exp)
def test_insert_item_cache(self, using_array_manager, using_copy_on_write): df = DataFrame(np.random.default_rng(2).standard_normal((4, 3))) ser = df[0]
if using_array_manager: expected_warning = None else: # with BlockManager warn about high fragmentation of single dtype expected_warning = PerformanceWarning
with tm.assert_produces_warning(expected_warning): for n in range(100): df[n + 3] = df[1] * n
if using_copy_on_write: ser.iloc[0] = 99 assert df.iloc[0, 0] == df[0][0] assert df.iloc[0, 0] != 99 else: ser.values[0] = 99 assert df.iloc[0, 0] == df[0][0] assert df.iloc[0, 0] == 99
def test_insert_EA_no_warning(self): # PerformanceWarning about fragmented frame should not be raised when # using EAs (https://github.com/pandas-dev/pandas/issues/44098) df = DataFrame( np.random.default_rng(2).integers(0, 100, size=(3, 100)), dtype="Int64" ) with tm.assert_produces_warning(None): df["a"] = np.array([1, 2, 3])
def test_insert_frame(self): # GH#42403 df = DataFrame({"col1": [1, 2], "col2": [3, 4]})
msg = ( "Expected a one-dimensional object, got a DataFrame with 2 columns instead." ) with pytest.raises(ValueError, match=msg): df.insert(1, "newcol", df)
def test_insert_int64_loc(self): # GH#53193 df = DataFrame({"a": [1, 2]}) df.insert(np.int64(0), "b", 0) tm.assert_frame_equal(df, DataFrame({"b": [0, 0], "a": [1, 2]}))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Tests for DataFrame.mask; tests DataFrame.where as a side-effect."""
import numpy as np
from pandas import ( NA, DataFrame, Float64Dtype, Series, StringDtype, Timedelta, isna,)import pandas._testing as tm
class TestDataFrameMask: def test_mask(self): df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) cond = df > 0
rs = df.where(cond, np.nan) tm.assert_frame_equal(rs, df.mask(df <= 0)) tm.assert_frame_equal(rs, df.mask(~cond))
other = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) rs = df.where(cond, other) tm.assert_frame_equal(rs, df.mask(df <= 0, other)) tm.assert_frame_equal(rs, df.mask(~cond, other))
def test_mask2(self): # see GH#21891 df = DataFrame([1, 2]) res = df.mask([[True], [False]])
exp = DataFrame([np.nan, 2]) tm.assert_frame_equal(res, exp)
def test_mask_inplace(self): # GH#8801 df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) cond = df > 0
rdf = df.copy()
return_value = rdf.where(cond, inplace=True) assert return_value is None tm.assert_frame_equal(rdf, df.where(cond)) tm.assert_frame_equal(rdf, df.mask(~cond))
rdf = df.copy() return_value = rdf.where(cond, -df, inplace=True) assert return_value is None tm.assert_frame_equal(rdf, df.where(cond, -df)) tm.assert_frame_equal(rdf, df.mask(~cond, -df))
def test_mask_edge_case_1xN_frame(self): # GH#4071 df = DataFrame([[1, 2]]) res = df.mask(DataFrame([[True, False]])) expec = DataFrame([[np.nan, 2]]) tm.assert_frame_equal(res, expec)
def test_mask_callable(self): # GH#12533 df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) result = df.mask(lambda x: x > 4, lambda x: x + 1) exp = DataFrame([[1, 2, 3], [4, 6, 7], [8, 9, 10]]) tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, df.mask(df > 4, df + 1))
# return ndarray and scalar result = df.mask(lambda x: (x % 2 == 0).values, lambda x: 99) exp = DataFrame([[1, 99, 3], [99, 5, 99], [7, 99, 9]]) tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, df.mask(df % 2 == 0, 99))
# chain result = (df + 2).mask(lambda x: x > 8, lambda x: x + 10) exp = DataFrame([[3, 4, 5], [6, 7, 8], [19, 20, 21]]) tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, (df + 2).mask((df + 2) > 8, (df + 2) + 10))
def test_mask_dtype_bool_conversion(self): # GH#3733 df = DataFrame(data=np.random.default_rng(2).standard_normal((100, 50))) df = df.where(df > 0) # create nans bools = df > 0 mask = isna(df) expected = bools.astype(object).mask(mask) result = bools.mask(mask) tm.assert_frame_equal(result, expected)
def test_mask_stringdtype(frame_or_series): # GH 40824 obj = DataFrame( {"A": ["foo", "bar", "baz", NA]}, index=["id1", "id2", "id3", "id4"], dtype=StringDtype(), ) filtered_obj = DataFrame( {"A": ["this", "that"]}, index=["id2", "id3"], dtype=StringDtype() ) expected = DataFrame( {"A": [NA, "this", "that", NA]}, index=["id1", "id2", "id3", "id4"], dtype=StringDtype(), ) if frame_or_series is Series: obj = obj["A"] filtered_obj = filtered_obj["A"] expected = expected["A"]
filter_ser = Series([False, True, True, False]) result = obj.mask(filter_ser, filtered_obj)
tm.assert_equal(result, expected)
def test_mask_where_dtype_timedelta(): # https://github.com/pandas-dev/pandas/issues/39548 df = DataFrame([Timedelta(i, unit="d") for i in range(5)])
expected = DataFrame(np.full(5, np.nan, dtype="timedelta64[ns]")) tm.assert_frame_equal(df.mask(df.notna()), expected)
expected = DataFrame( [np.nan, np.nan, np.nan, Timedelta("3 day"), Timedelta("4 day")] ) tm.assert_frame_equal(df.where(df > Timedelta(2, unit="d")), expected)
def test_mask_return_dtype(): # GH#50488 ser = Series([0.0, 1.0, 2.0, 3.0], dtype=Float64Dtype()) cond = ~ser.isna() other = Series([True, False, True, False]) excepted = Series([1.0, 0.0, 1.0, 0.0], dtype=ser.dtype) result = ser.mask(cond, other) tm.assert_series_equal(result, excepted)
def test_mask_inplace_no_other(): # GH#51685 df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]}) cond = DataFrame({"a": [True, False], "b": [False, True]}) df.mask(cond, inplace=True) expected = DataFrame({"a": [np.nan, 2], "b": ["x", np.nan]}) tm.assert_frame_equal(df, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import numpy as np
from pandas.core.dtypes.common import is_float_dtype
from pandas import ( DataFrame, isna,)import pandas._testing as tm
class TestSetValue: def test_set_value(self, float_frame): for idx in float_frame.index: for col in float_frame.columns: float_frame._set_value(idx, col, 1) assert float_frame[col][idx] == 1
def test_set_value_resize(self, float_frame, using_infer_string): res = float_frame._set_value("foobar", "B", 0) assert res is None assert float_frame.index[-1] == "foobar" assert float_frame._get_value("foobar", "B") == 0
float_frame.loc["foobar", "qux"] = 0 assert float_frame._get_value("foobar", "qux") == 0
res = float_frame.copy() res._set_value("foobar", "baz", "sam") if using_infer_string: assert res["baz"].dtype == "string" else: assert res["baz"].dtype == np.object_ res = float_frame.copy() res._set_value("foobar", "baz", True) assert res["baz"].dtype == np.object_
res = float_frame.copy() res._set_value("foobar", "baz", 5) assert is_float_dtype(res["baz"]) assert isna(res["baz"].drop(["foobar"])).all()
with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): res._set_value("foobar", "baz", "sam") assert res.loc["foobar", "baz"] == "sam"
def test_set_value_with_index_dtype_change(self): df_orig = DataFrame( np.random.default_rng(2).standard_normal((3, 3)), index=range(3), columns=list("ABC"), )
# this is actually ambiguous as the 2 is interpreted as a positional # so column is not created df = df_orig.copy() df._set_value("C", 2, 1.0) assert list(df.index) == list(df_orig.index) + ["C"] # assert list(df.columns) == list(df_orig.columns) + [2]
df = df_orig.copy() df.loc["C", 2] = 1.0 assert list(df.index) == list(df_orig.index) + ["C"] # assert list(df.columns) == list(df_orig.columns) + [2]
# create both new df = df_orig.copy() df._set_value("C", "D", 1.0) assert list(df.index) == list(df_orig.index) + ["C"] assert list(df.columns) == list(df_orig.columns) + ["D"]
df = df_orig.copy() df.loc["C", "D"] = 1.0 assert list(df.index) == list(df_orig.index) + ["C"] assert list(df.columns) == list(df_orig.columns) + ["D"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419from datetime import datetime
import numpy as npimport pytest
import pandas.util._test_decorators as td
from pandas.core.dtypes.base import _registry as ea_registryfrom pandas.core.dtypes.common import is_object_dtypefrom pandas.core.dtypes.dtypes import ( CategoricalDtype, DatetimeTZDtype, IntervalDtype, PeriodDtype,)
import pandas as pdfrom pandas import ( Categorical, DataFrame, DatetimeIndex, Index, Interval, IntervalIndex, MultiIndex, NaT, Period, PeriodIndex, Series, Timestamp, cut, date_range, notna, period_range,)import pandas._testing as tmfrom pandas.core.arrays import SparseArray
from pandas.tseries.offsets import BDay
class TestDataFrameSetItem: def test_setitem_str_subclass(self): # GH#37366 class mystring(str): pass
data = ["2020-10-22 01:21:00+00:00"] index = DatetimeIndex(data) df = DataFrame({"a": [1]}, index=index) df["b"] = 2 df[mystring("c")] = 3 expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index) tm.assert_equal(df, expected)
@pytest.mark.parametrize( "dtype", ["int32", "int64", "uint32", "uint64", "float32", "float64"] ) def test_setitem_dtype(self, dtype, float_frame): # Use integers since casting negative floats to uints is undefined arr = np.random.default_rng(2).integers(1, 10, len(float_frame))
float_frame[dtype] = np.array(arr, dtype=dtype) assert float_frame[dtype].dtype.name == dtype
def test_setitem_list_not_dataframe(self, float_frame): data = np.random.default_rng(2).standard_normal((len(float_frame), 2)) float_frame[["A", "B"]] = data tm.assert_almost_equal(float_frame[["A", "B"]].values, data)
def test_setitem_error_msmgs(self): # GH 7432 df = DataFrame( {"bar": [1, 2, 3], "baz": ["d", "e", "f"]}, index=Index(["a", "b", "c"], name="foo"), ) ser = Series( ["g", "h", "i", "j"], index=Index(["a", "b", "c", "a"], name="foo"), name="fiz", ) msg = "cannot reindex on an axis with duplicate labels" with pytest.raises(ValueError, match=msg): df["newcol"] = ser
# GH 4107, more descriptive error message df = DataFrame( np.random.default_rng(2).integers(0, 2, (4, 4)), columns=["a", "b", "c", "d"], )
msg = "Cannot set a DataFrame with multiple columns to the single column gr" with pytest.raises(ValueError, match=msg): df["gr"] = df.groupby(["b", "c"]).count()
# GH 55956, specific message for zero columns msg = "Cannot set a DataFrame without columns to the column gr" with pytest.raises(ValueError, match=msg): df["gr"] = DataFrame()
def test_setitem_benchmark(self): # from the vb_suite/frame_methods/frame_insert_columns N = 10 K = 5 df = DataFrame(index=range(N)) new_col = np.random.default_rng(2).standard_normal(N) for i in range(K): df[i] = new_col expected = DataFrame(np.repeat(new_col, K).reshape(N, K), index=range(N)) tm.assert_frame_equal(df, expected)
def test_setitem_different_dtype(self): df = DataFrame( np.random.default_rng(2).standard_normal((5, 3)), index=np.arange(5), columns=["c", "b", "a"], ) df.insert(0, "foo", df["a"]) df.insert(2, "bar", df["c"])
# diff dtype
# new item df["x"] = df["a"].astype("float32") result = df.dtypes expected = Series( [np.dtype("float64")] * 5 + [np.dtype("float32")], index=["foo", "c", "bar", "b", "a", "x"], ) tm.assert_series_equal(result, expected)
# replacing current (in different block) df["a"] = df["a"].astype("float32") result = df.dtypes expected = Series( [np.dtype("float64")] * 4 + [np.dtype("float32")] * 2, index=["foo", "c", "bar", "b", "a", "x"], ) tm.assert_series_equal(result, expected)
df["y"] = df["a"].astype("int32") result = df.dtypes expected = Series( [np.dtype("float64")] * 4 + [np.dtype("float32")] * 2 + [np.dtype("int32")], index=["foo", "c", "bar", "b", "a", "x", "y"], ) tm.assert_series_equal(result, expected)
def test_setitem_empty_columns(self): # GH 13522 df = DataFrame(index=["A", "B", "C"]) df["X"] = df.index df["X"] = ["x", "y", "z"] exp = DataFrame(data={"X": ["x", "y", "z"]}, index=["A", "B", "C"]) tm.assert_frame_equal(df, exp)
def test_setitem_dt64_index_empty_columns(self): rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") df = DataFrame(index=np.arange(len(rng)))
df["A"] = rng assert df["A"].dtype == np.dtype("M8[ns]")
def test_setitem_timestamp_empty_columns(self): # GH#19843 df = DataFrame(index=range(3)) df["now"] = Timestamp("20130101", tz="UTC").as_unit("ns")
expected = DataFrame( [[Timestamp("20130101", tz="UTC")]] * 3, index=[0, 1, 2], columns=["now"] ) tm.assert_frame_equal(df, expected)
def test_setitem_wrong_length_categorical_dtype_raises(self): # GH#29523 cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) df = DataFrame(range(10), columns=["bar"])
msg = ( rf"Length of values \({len(cat)}\) " rf"does not match length of index \({len(df)}\)" ) with pytest.raises(ValueError, match=msg): df["foo"] = cat
def test_setitem_with_sparse_value(self): # GH#8131 df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) sp_array = SparseArray([0, 0, 1]) df["new_column"] = sp_array
expected = Series(sp_array, name="new_column") tm.assert_series_equal(df["new_column"], expected)
def test_setitem_with_unaligned_sparse_value(self): df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0])
df["new_column"] = sp_series expected = Series(SparseArray([1, 0, 0]), name="new_column") tm.assert_series_equal(df["new_column"], expected)
def test_setitem_period_preserves_dtype(self): # GH: 26861 data = [Period("2003-12", "D")] result = DataFrame([]) result["a"] = data
expected = DataFrame({"a": data})
tm.assert_frame_equal(result, expected)
def test_setitem_dict_preserves_dtypes(self): # https://github.com/pandas-dev/pandas/issues/34573 expected = DataFrame( { "a": Series([0, 1, 2], dtype="int64"), "b": Series([1, 2, 3], dtype=float), "c": Series([1, 2, 3], dtype=float), "d": Series([1, 2, 3], dtype="uint32"), } ) df = DataFrame( { "a": Series([], dtype="int64"), "b": Series([], dtype=float), "c": Series([], dtype=float), "d": Series([], dtype="uint32"), } ) for idx, b in enumerate([1, 2, 3]): df.loc[df.shape[0]] = { "a": int(idx), "b": float(b), "c": float(b), "d": np.uint32(b), } tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( "obj,dtype", [ (Period("2020-01"), PeriodDtype("M")), (Interval(left=0, right=5), IntervalDtype("int64", "right")), ( Timestamp("2011-01-01", tz="US/Eastern"), DatetimeTZDtype(unit="s", tz="US/Eastern"), ), ], ) def test_setitem_extension_types(self, obj, dtype): # GH: 34832 expected = DataFrame({"idx": [1, 2, 3], "obj": Series([obj] * 3, dtype=dtype)})
df = DataFrame({"idx": [1, 2, 3]}) df["obj"] = obj
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( "ea_name", [ dtype.name for dtype in ea_registry.dtypes # property would require instantiation if not isinstance(dtype.name, property) ] + ["datetime64[ns, UTC]", "period[D]"], ) def test_setitem_with_ea_name(self, ea_name): # GH 38386 result = DataFrame([0]) result[ea_name] = [1] expected = DataFrame({0: [0], ea_name: [1]}) tm.assert_frame_equal(result, expected)
def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self): # GH#7492 data_ns = np.array([1, "nat"], dtype="datetime64[ns]") result = Series(data_ns).to_frame() result["new"] = data_ns expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]") tm.assert_frame_equal(result, expected)
# OutOfBoundsDatetime error shouldn't occur; as of 2.0 we preserve "M8[s]" data_s = np.array([1, "nat"], dtype="datetime64[s]") result["new"] = data_s tm.assert_series_equal(result[0], expected[0]) tm.assert_numpy_array_equal(result["new"].to_numpy(), data_s)
@pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) def test_frame_setitem_datetime64_col_other_units(self, unit): # Check that non-nano dt64 values get cast to dt64 on setitem # into a not-yet-existing column n = 100
dtype = np.dtype(f"M8[{unit}]") vals = np.arange(n, dtype=np.int64).view(dtype) if unit in ["s", "ms"]: # supported unit ex_vals = vals else: # we get the nearest supported units, i.e. "s" ex_vals = vals.astype("datetime64[s]")
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) df[unit] = vals
assert df[unit].dtype == ex_vals.dtype assert (df[unit].values == ex_vals).all()
@pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) def test_frame_setitem_existing_datetime64_col_other_units(self, unit): # Check that non-nano dt64 values get cast to dt64 on setitem # into an already-existing dt64 column n = 100
dtype = np.dtype(f"M8[{unit}]") vals = np.arange(n, dtype=np.int64).view(dtype) ex_vals = vals.astype("datetime64[ns]")
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) df["dates"] = np.arange(n, dtype=np.int64).view("M8[ns]")
# We overwrite existing dt64 column with new, non-nano dt64 vals df["dates"] = vals assert (df["dates"].values == ex_vals).all()
def test_setitem_dt64tz(self, timezone_frame, using_copy_on_write): df = timezone_frame idx = df["B"].rename("foo")
# setitem df["C"] = idx tm.assert_series_equal(df["C"], Series(idx, name="C"))
df["D"] = "foo" df["D"] = idx tm.assert_series_equal(df["D"], Series(idx, name="D")) del df["D"]
# assert that A & C are not sharing the same base (e.g. they # are copies) # Note: This does not hold with Copy on Write (because of lazy copying) v1 = df._mgr.arrays[1] v2 = df._mgr.arrays[2] tm.assert_extension_array_equal(v1, v2) v1base = v1._ndarray.base v2base = v2._ndarray.base if not using_copy_on_write: assert v1base is None or (id(v1base) != id(v2base)) else: assert id(v1base) == id(v2base)
# with nan df2 = df.copy() df2.iloc[1, 1] = NaT df2.iloc[1, 2] = NaT result = df2["B"] tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) tm.assert_series_equal(df2.dtypes, df.dtypes)
def test_setitem_periodindex(self): rng = period_range("1/1/2000", periods=5, name="index") df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), index=rng)
df["Index"] = rng rs = Index(df["Index"]) tm.assert_index_equal(rs, rng, check_names=False) assert rs.name == "Index" assert rng.name == "index"
rs = df.reset_index().set_index("index") assert isinstance(rs.index, PeriodIndex) tm.assert_index_equal(rs.index, rng)
def test_setitem_complete_column_with_array(self): # GH#37954 df = DataFrame({"a": ["one", "two", "three"], "b": [1, 2, 3]}) arr = np.array([[1, 1], [3, 1], [5, 1]]) df[["c", "d"]] = arr expected = DataFrame( { "a": ["one", "two", "three"], "b": [1, 2, 3], "c": [1, 3, 5], "d": [1, 1, 1], } ) expected["c"] = expected["c"].astype(arr.dtype) expected["d"] = expected["d"].astype(arr.dtype) assert expected["c"].dtype == arr.dtype assert expected["d"].dtype == arr.dtype tm.assert_frame_equal(df, expected)
def test_setitem_period_d_dtype(self): # GH 39763 rng = period_range("2016-01-01", periods=9, freq="D", name="A") result = DataFrame(rng) expected = DataFrame( {"A": ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT"]}, dtype="period[D]", ) result.iloc[:] = rng._na_value tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("dtype", ["f8", "i8", "u8"]) def test_setitem_bool_with_numeric_index(self, dtype): # GH#36319 cols = Index([1, 2, 3], dtype=dtype) df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)), columns=cols)
df[False] = ["a", "b", "c"]
expected_cols = Index([1, 2, 3, False], dtype=object) if dtype == "f8": expected_cols = Index([1.0, 2.0, 3.0, False], dtype=object)
tm.assert_index_equal(df.columns, expected_cols)
@pytest.mark.parametrize("indexer", ["B", ["B"]]) def test_setitem_frame_length_0_str_key(self, indexer): # GH#38831 df = DataFrame(columns=["A", "B"]) other = DataFrame({"B": [1, 2]}) df[indexer] = other expected = DataFrame({"A": [np.nan] * 2, "B": [1, 2]}) expected["A"] = expected["A"].astype("object") tm.assert_frame_equal(df, expected)
def test_setitem_frame_duplicate_columns(self): # GH#15695 cols = ["A", "B", "C"] * 2 df = DataFrame(index=range(3), columns=cols) df.loc[0, "A"] = (0, 3) df.loc[:, "B"] = (1, 4) df["C"] = (2, 5) expected = DataFrame( [ [0, 1, 2, 3, 4, 5], [np.nan, 1, 2, np.nan, 4, 5], [np.nan, 1, 2, np.nan, 4, 5], ], dtype="object", )
# set these with unique columns to be extra-unambiguous expected[2] = expected[2].astype(np.int64) expected[5] = expected[5].astype(np.int64) expected.columns = cols
tm.assert_frame_equal(df, expected)
def test_setitem_frame_duplicate_columns_size_mismatch(self): # GH#39510 cols = ["A", "B", "C"] * 2 df = DataFrame(index=range(3), columns=cols) with pytest.raises(ValueError, match="Columns must be same length as key"): df[["A"]] = (0, 3, 5)
df2 = df.iloc[:, :3] # unique columns with pytest.raises(ValueError, match="Columns must be same length as key"): df2[["A"]] = (0, 3, 5)
@pytest.mark.parametrize("cols", [["a", "b", "c"], ["a", "a", "a"]]) def test_setitem_df_wrong_column_number(self, cols): # GH#38604 df = DataFrame([[1, 2, 3]], columns=cols) rhs = DataFrame([[10, 11]], columns=["d", "e"]) msg = "Columns must be same length as key" with pytest.raises(ValueError, match=msg): df["a"] = rhs
def test_setitem_listlike_indexer_duplicate_columns(self): # GH#38604 df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"]) rhs = DataFrame([[10, 11, 12]], columns=["a", "b", "b"]) df[["a", "b"]] = rhs expected = DataFrame([[10, 11, 12]], columns=["a", "b", "b"]) tm.assert_frame_equal(df, expected)
df[["c", "b"]] = rhs expected = DataFrame([[10, 11, 12, 10]], columns=["a", "b", "b", "c"]) tm.assert_frame_equal(df, expected)
def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self): # GH#39403 df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"]) rhs = DataFrame([[10, 11]], columns=["a", "b"]) msg = "Columns must be same length as key" with pytest.raises(ValueError, match=msg): df[["a", "b"]] = rhs
def test_setitem_intervals(self): df = DataFrame({"A": range(10)}) ser = cut(df["A"], 5) assert isinstance(ser.cat.categories, IntervalIndex)
# B & D end up as Categoricals # the remainder are converted to in-line objects # containing an IntervalIndex.values df["B"] = ser df["C"] = np.array(ser) df["D"] = ser.values df["E"] = np.array(ser.values) df["F"] = ser.astype(object)
assert isinstance(df["B"].dtype, CategoricalDtype) assert isinstance(df["B"].cat.categories.dtype, IntervalDtype) assert isinstance(df["D"].dtype, CategoricalDtype) assert isinstance(df["D"].cat.categories.dtype, IntervalDtype)
# These go through the Series constructor and so get inferred back # to IntervalDtype assert isinstance(df["C"].dtype, IntervalDtype) assert isinstance(df["E"].dtype, IntervalDtype)
# But the Series constructor doesn't do inference on Series objects, # so setting df["F"] doesn't get cast back to IntervalDtype assert is_object_dtype(df["F"])
# they compare equal as Index # when converted to numpy objects c = lambda x: Index(np.array(x)) tm.assert_index_equal(c(df.B), c(df.B)) tm.assert_index_equal(c(df.B), c(df.C), check_names=False) tm.assert_index_equal(c(df.B), c(df.D), check_names=False) tm.assert_index_equal(c(df.C), c(df.D), check_names=False)
# B & D are the same Series tm.assert_series_equal(df["B"], df["B"]) tm.assert_series_equal(df["B"], df["D"], check_names=False)
# C & E are the same Series tm.assert_series_equal(df["C"], df["C"]) tm.assert_series_equal(df["C"], df["E"], check_names=False)
def test_setitem_categorical(self): # GH#35369 df = DataFrame({"h": Series(list("mn")).astype("category")}) df.h = df.h.cat.reorder_categories(["n", "m"]) expected = DataFrame( {"h": Categorical(["m", "n"]).reorder_categories(["n", "m"])} ) tm.assert_frame_equal(df, expected)
def test_setitem_with_empty_listlike(self): # GH#17101 index = Index([], name="idx") result = DataFrame(columns=["A"], index=index) result["A"] = [] expected = DataFrame(columns=["A"], index=index) tm.assert_index_equal(result.index, expected.index)
@pytest.mark.parametrize( "cols, values, expected", [ (["C", "D", "D", "a"], [1, 2, 3, 4], 4), # with duplicates (["D", "C", "D", "a"], [1, 2, 3, 4], 4), # mixed order (["C", "B", "B", "a"], [1, 2, 3, 4], 4), # other duplicate cols (["C", "B", "a"], [1, 2, 3], 3), # no duplicates (["B", "C", "a"], [3, 2, 1], 1), # alphabetical order (["C", "a", "B"], [3, 2, 1], 2), # in the middle ], ) def test_setitem_same_column(self, cols, values, expected): # GH#23239 df = DataFrame([values], columns=cols) df["a"] = df["a"] result = df["a"].values[0] assert result == expected
def test_setitem_multi_index(self): # GH#7655, test that assigning to a sub-frame of a frame # with multi-index columns aligns both rows and columns it = ["jim", "joe", "jolie"], ["first", "last"], ["left", "center", "right"]
cols = MultiIndex.from_product(it) index = date_range("20141006", periods=20) vals = np.random.default_rng(2).integers(1, 1000, (len(index), len(cols))) df = DataFrame(vals, columns=cols, index=index)
i, j = df.index.values.copy(), it[-1][:]
np.random.default_rng(2).shuffle(i) df["jim"] = df["jolie"].loc[i, ::-1] tm.assert_frame_equal(df["jim"], df["jolie"])
np.random.default_rng(2).shuffle(j) df[("joe", "first")] = df[("jolie", "last")].loc[i, j] tm.assert_frame_equal(df[("joe", "first")], df[("jolie", "last")])
np.random.default_rng(2).shuffle(j) df[("joe", "last")] = df[("jolie", "first")].loc[i, j] tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")])
@pytest.mark.parametrize( "columns,box,expected", [ ( ["A", "B", "C", "D"], 7, DataFrame( [[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]], columns=["A", "B", "C", "D"], ), ), ( ["C", "D"], [7, 8], DataFrame( [[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]], columns=["A", "B", "C", "D"], ), ), ( ["A", "B", "C"], np.array([7, 8, 9], dtype=np.int64), DataFrame([[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"]), ), ( ["B", "C", "D"], [[7, 8, 9], [10, 11, 12], [13, 14, 15]], DataFrame( [[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]], columns=["A", "B", "C", "D"], ), ), ( ["C", "A", "D"], np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64), DataFrame( [[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]], columns=["A", "B", "C", "D"], ), ), ( ["A", "C"], DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]), DataFrame( [[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"] ), ), ], ) def test_setitem_list_missing_columns(self, columns, box, expected): # GH#29334 df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"]) df[columns] = box tm.assert_frame_equal(df, expected)
def test_setitem_list_of_tuples(self, float_frame): tuples = list(zip(float_frame["A"], float_frame["B"])) float_frame["tuples"] = tuples
result = float_frame["tuples"] expected = Series(tuples, index=float_frame.index, name="tuples") tm.assert_series_equal(result, expected)
def test_setitem_iloc_generator(self): # GH#39614 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) indexer = (x for x in [1, 2]) df.iloc[indexer] = 1 expected = DataFrame({"a": [1, 1, 1], "b": [4, 1, 1]}) tm.assert_frame_equal(df, expected)
def test_setitem_iloc_two_dimensional_generator(self): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) indexer = (x for x in [1, 2]) df.iloc[indexer, 1] = 1 expected = DataFrame({"a": [1, 2, 3], "b": [4, 1, 1]}) tm.assert_frame_equal(df, expected)
def test_setitem_dtypes_bytes_type_to_object(self): # GH 20734 index = Series(name="id", dtype="S24") df = DataFrame(index=index) df["a"] = Series(name="a", index=index, dtype=np.uint32) df["b"] = Series(name="b", index=index, dtype="S64") df["c"] = Series(name="c", index=index, dtype="S64") df["d"] = Series(name="d", index=index, dtype=np.uint8) result = df.dtypes expected = Series([np.uint32, object, object, np.uint8], index=list("abcd")) tm.assert_series_equal(result, expected)
def test_boolean_mask_nullable_int64(self): # GH 28928 result = DataFrame({"a": [3, 4], "b": [5, 6]}).astype( {"a": "int64", "b": "Int64"} ) mask = Series(False, index=result.index) result.loc[mask, "a"] = result["a"] result.loc[mask, "b"] = result["b"] expected = DataFrame({"a": [3, 4], "b": [5, 6]}).astype( {"a": "int64", "b": "Int64"} ) tm.assert_frame_equal(result, expected)
def test_setitem_ea_dtype_rhs_series(self): # GH#47425 df = DataFrame({"a": [1, 2]}) df["a"] = Series([1, 2], dtype="Int64") expected = DataFrame({"a": [1, 2]}, dtype="Int64") tm.assert_frame_equal(df, expected)
# TODO(ArrayManager) set column with 2d column array, see #44788 @td.skip_array_manager_not_yet_implemented def test_setitem_npmatrix_2d(self): # GH#42376 # for use-case df["x"] = sparse.random((10, 10)).mean(axis=1) expected = DataFrame( {"np-array": np.ones(10), "np-matrix": np.ones(10)}, index=np.arange(10) )
a = np.ones((10, 1)) df = DataFrame(index=np.arange(10)) df["np-array"] = a
# Instantiation of `np.matrix` gives PendingDeprecationWarning with tm.assert_produces_warning(PendingDeprecationWarning): df["np-matrix"] = np.matrix(a)
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("vals", [{}, {"d": "a"}]) def test_setitem_aligning_dict_with_index(self, vals): # GH#47216 df = DataFrame({"a": [1, 2], "b": [3, 4], **vals}) df.loc[:, "a"] = {1: 100, 0: 200} df.loc[:, "c"] = {0: 5, 1: 6} df.loc[:, "e"] = {1: 5} expected = DataFrame( {"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6], "e": [np.nan, 5]} ) tm.assert_frame_equal(df, expected)
def test_setitem_rhs_dataframe(self): # GH#47578 df = DataFrame({"a": [1, 2]}) df["a"] = DataFrame({"a": [10, 11]}, index=[1, 2]) expected = DataFrame({"a": [np.nan, 10]}) tm.assert_frame_equal(df, expected)
df = DataFrame({"a": [1, 2]}) df.isetitem(0, DataFrame({"a": [10, 11]}, index=[1, 2])) tm.assert_frame_equal(df, expected)
def test_setitem_frame_overwrite_with_ea_dtype(self, any_numeric_ea_dtype): # GH#46896 df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]]) df["a"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype) expected = DataFrame( { "a": Series([10, 11], dtype=any_numeric_ea_dtype), "b": [2, 4], } ) tm.assert_frame_equal(df, expected)
def test_setitem_string_option_object_index(self): # GH#55638 pytest.importorskip("pyarrow") df = DataFrame({"a": [1, 2]}) with pd.option_context("future.infer_string", True): df["b"] = Index(["a", "b"], dtype=object) expected = DataFrame({"a": [1, 2], "b": Series(["a", "b"], dtype=object)}) tm.assert_frame_equal(df, expected)
def test_setitem_frame_midx_columns(self): # GH#49121 df = DataFrame({("a", "b"): [10]}) expected = df.copy() col_name = ("a", "b") df[col_name] = df[[col_name]] tm.assert_frame_equal(df, expected)
def test_loc_setitem_ea_dtype(self): # GH#55604 df = DataFrame({"a": np.array([10], dtype="i8")}) df.loc[:, "a"] = Series([11], dtype="Int64") expected = DataFrame({"a": np.array([11], dtype="i8")}) tm.assert_frame_equal(df, expected)
df = DataFrame({"a": np.array([10], dtype="i8")}) df.iloc[:, 0] = Series([11], dtype="Int64") tm.assert_frame_equal(df, expected)
def test_setitem_object_inferring(self): # GH#56102 idx = Index([Timestamp("2019-12-31")], dtype=object) df = DataFrame({"a": [1]}) with tm.assert_produces_warning(FutureWarning, match="infer"): df.loc[:, "b"] = idx with tm.assert_produces_warning(FutureWarning, match="infer"): df["c"] = idx
expected = DataFrame( { "a": [1], "b": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"), "c": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"), } ) tm.assert_frame_equal(df, expected)
class TestSetitemTZAwareValues: @pytest.fixture def idx(self): naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") idx = naive.tz_localize("US/Pacific") return idx
@pytest.fixture def expected(self, idx): expected = Series(np.array(idx.tolist(), dtype="object"), name="B") assert expected.dtype == idx.dtype return expected
def test_setitem_dt64series(self, idx, expected): # convert to utc df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"]) df["B"] = idx df["B"] = idx.to_series(index=[0, 1]).dt.tz_convert(None)
result = df["B"] comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B") tm.assert_series_equal(result, comp)
def test_setitem_datetimeindex(self, idx, expected): # setting a DataFrame column with a tzaware DTI retains the dtype df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])
# assign to frame df["B"] = idx result = df["B"] tm.assert_series_equal(result, expected)
def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected): # setting a DataFrame column with a tzaware DTI retains the dtype df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])
# object array of datetimes with a tz df["B"] = idx.to_pydatetime() result = df["B"] tm.assert_series_equal(result, expected)
class TestDataFrameSetItemWithExpansion: def test_setitem_listlike_views(self, using_copy_on_write, warn_copy_on_write): # GH#38148 df = DataFrame({"a": [1, 2, 3], "b": [4, 4, 6]})
# get one column as a view of df ser = df["a"]
# add columns with list-like indexer df[["c", "d"]] = np.array([[0.1, 0.2], [0.3, 0.4], [0.4, 0.5]])
# edit in place the first column to check view semantics with tm.assert_cow_warning(warn_copy_on_write): df.iloc[0, 0] = 100
if using_copy_on_write: expected = Series([1, 2, 3], name="a") else: expected = Series([100, 2, 3], name="a") tm.assert_series_equal(ser, expected)
def test_setitem_string_column_numpy_dtype_raising(self): # GH#39010 df = DataFrame([[1, 2], [3, 4]]) df["0 - Name"] = [5, 6] expected = DataFrame([[1, 2, 5], [3, 4, 6]], columns=[0, 1, "0 - Name"]) tm.assert_frame_equal(df, expected)
def test_setitem_empty_df_duplicate_columns(self, using_copy_on_write): # GH#38521 df = DataFrame(columns=["a", "b", "b"], dtype="float64") df.loc[:, "a"] = list(range(2)) expected = DataFrame( [[0, np.nan, np.nan], [1, np.nan, np.nan]], columns=["a", "b", "b"] ) tm.assert_frame_equal(df, expected)
def test_setitem_with_expansion_categorical_dtype(self): # assignment df = DataFrame( { "value": np.array( np.random.default_rng(2).integers(0, 10000, 100), dtype="int32" ) } ) labels = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)])
df = df.sort_values(by=["value"], ascending=True) ser = cut(df.value, range(0, 10500, 500), right=False, labels=labels) cat = ser.values
# setting with a Categorical df["D"] = cat result = df.dtypes expected = Series( [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], index=["value", "D"], ) tm.assert_series_equal(result, expected)
# setting with a Series df["E"] = ser result = df.dtypes expected = Series( [ np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False), CategoricalDtype(categories=labels, ordered=False), ], index=["value", "D", "E"], ) tm.assert_series_equal(result, expected)
result1 = df["D"] result2 = df["E"] tm.assert_categorical_equal(result1._mgr.array, cat)
# sorting ser.name = "E" tm.assert_series_equal(result2.sort_index(), ser.sort_index())
def test_setitem_scalars_no_index(self): # GH#16823 / GH#17894 df = DataFrame() df["foo"] = 1 expected = DataFrame(columns=["foo"]).astype(np.int64) tm.assert_frame_equal(df, expected)
def test_setitem_newcol_tuple_key(self, float_frame): assert ( "A", "B", ) not in float_frame.columns float_frame["A", "B"] = float_frame["A"] assert ("A", "B") in float_frame.columns
result = float_frame["A", "B"] expected = float_frame["A"] tm.assert_series_equal(result, expected, check_names=False)
def test_frame_setitem_newcol_timestamp(self): # GH#2155 columns = date_range(start="1/1/2012", end="2/1/2012", freq=BDay()) data = DataFrame(columns=columns, index=range(10)) t = datetime(2012, 11, 1) ts = Timestamp(t) data[ts] = np.nan # works, mostly a smoke-test assert np.isnan(data[ts]).all()
def test_frame_setitem_rangeindex_into_new_col(self): # GH#47128 df = DataFrame({"a": ["a", "b"]}) df["b"] = df.index df.loc[[False, True], "b"] = 100 result = df.loc[[1], :] expected = DataFrame({"a": ["b"], "b": [100]}, index=[1]) tm.assert_frame_equal(result, expected)
def test_setitem_frame_keep_ea_dtype(self, any_numeric_ea_dtype): # GH#46896 df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]]) df["c"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype) expected = DataFrame( { "a": [1, 3], "b": [2, 4], "c": Series([10, 11], dtype=any_numeric_ea_dtype), } ) tm.assert_frame_equal(df, expected)
def test_loc_expansion_with_timedelta_type(self): result = DataFrame(columns=list("abc")) result.loc[0] = { "a": pd.to_timedelta(5, unit="s"), "b": pd.to_timedelta(72, unit="s"), "c": "23", } expected = DataFrame( [[pd.Timedelta("0 days 00:00:05"), pd.Timedelta("0 days 00:01:12"), "23"]], index=Index([0]), columns=(["a", "b", "c"]), ) tm.assert_frame_equal(result, expected)
class TestDataFrameSetItemSlicing: def test_setitem_slice_position(self): # GH#31469 df = DataFrame(np.zeros((100, 1))) df[-4:] = 1 arr = np.zeros((100, 1)) arr[-4:] = 1 expected = DataFrame(arr) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc]) @pytest.mark.parametrize("box", [Series, np.array, list, pd.array]) @pytest.mark.parametrize("n", [1, 2, 3]) def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer): # GH#40440 df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]) indexer(df)[1:] = box([10, 11, 12]) expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"]) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("box", [Series, np.array, list, pd.array]) @pytest.mark.parametrize("n", [1, 2, 3]) def test_setitem_list_indexer_broadcasting_rhs(self, n, box): # GH#40440 df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]) df.iloc[list(range(1, n + 1))] = box([10, 11, 12]) expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"]) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc]) @pytest.mark.parametrize("box", [Series, np.array, list, pd.array]) @pytest.mark.parametrize("n", [1, 2, 3]) def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer): # GH#40440 df = DataFrame( [[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"] ) indexer(df)[1:] = box([10, 11, 12]) expected = DataFrame( [[1, 3, 5]] + [[10, 11, 12]] * (n + 1), columns=["a", "b", "c"], dtype="object", ) tm.assert_frame_equal(df, expected)
class TestDataFrameSetItemCallable: def test_setitem_callable(self): # GH#12533 df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}) df[lambda x: "A"] = [11, 12, 13, 14]
exp = DataFrame({"A": [11, 12, 13, 14], "B": [5, 6, 7, 8]}) tm.assert_frame_equal(df, exp)
def test_setitem_other_callable(self): # GH#13299 def inc(x): return x + 1
# Set dtype object straight away to avoid upcast when setting inc below df = DataFrame([[-1, 1], [1, -1]], dtype=object) df[df > 0] = inc
expected = DataFrame([[-1, inc], [inc, -1]]) tm.assert_frame_equal(df, expected)
class TestDataFrameSetItemBooleanMask: @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values @pytest.mark.parametrize( "mask_type", [lambda df: df > np.abs(df) / 2, lambda df: (df > np.abs(df) / 2).values], ids=["dataframe", "array"], ) def test_setitem_boolean_mask(self, mask_type, float_frame): # Test for issue #18582 df = float_frame.copy() mask = mask_type(df)
# index with boolean mask result = df.copy() result[mask] = np.nan
expected = df.values.copy() expected[np.array(mask)] = np.nan expected = DataFrame(expected, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(reason="Currently empty indexers are treated as all False") @pytest.mark.parametrize("box", [list, np.array, Series]) def test_setitem_loc_empty_indexer_raises_with_non_empty_value(self, box): # GH#37672 df = DataFrame({"a": ["a"], "b": [1], "c": [1]}) if box == Series: indexer = box([], dtype="object") else: indexer = box([]) msg = "Must have equal len keys and value when setting with an iterable" with pytest.raises(ValueError, match=msg): df.loc[indexer, ["b"]] = [1]
@pytest.mark.parametrize("box", [list, np.array, Series]) def test_setitem_loc_only_false_indexer_dtype_changed(self, box): # GH#37550 # Dtype is only changed when value to set is a Series and indexer is # empty/bool all False df = DataFrame({"a": ["a"], "b": [1], "c": [1]}) indexer = box([False]) df.loc[indexer, ["b"]] = 10 - df["c"] expected = DataFrame({"a": ["a"], "b": [1], "c": [1]}) tm.assert_frame_equal(df, expected)
df.loc[indexer, ["b"]] = 9 tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("indexer", [tm.setitem, tm.loc]) def test_setitem_boolean_mask_aligning(self, indexer): # GH#39931 df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]}) expected = df.copy() mask = df["a"] >= 3 indexer(df)[mask] = indexer(df)[mask].sort_values("a") tm.assert_frame_equal(df, expected)
def test_setitem_mask_categorical(self): # assign multiple rows (mixed values) (-> array) -> exp_multi_row # changed multiple rows cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) values2 = [1, 1, 2, 2, 1, 1, 1] exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
catsf = Categorical( ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] ) idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) valuesf = [1, 1, 3, 3, 1, 1, 1] df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf)
exp_fancy = exp_multi_row.copy() exp_fancy["cats"] = exp_fancy["cats"].cat.set_categories(["a", "b", "c"])
mask = df["cats"] == "c" df[mask] = ["b", 2] # category c is kept in .categories tm.assert_frame_equal(df, exp_fancy)
@pytest.mark.parametrize("dtype", ["float", "int64"]) @pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}]) def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): # see GH#10126 kwargs["dtype"] = dtype df = DataFrame(**kwargs)
df2 = df.copy() df[df > df2] = 47 tm.assert_frame_equal(df, df2)
def test_setitem_boolean_indexing(self): idx = list(range(3)) cols = ["A", "B", "C"] df1 = DataFrame( index=idx, columns=cols, data=np.array( [[0.0, 0.5, 1.0], [1.5, 2.0, 2.5], [3.0, 3.5, 4.0]], dtype=float ), ) df2 = DataFrame(index=idx, columns=cols, data=np.ones((len(idx), len(cols))))
expected = DataFrame( index=idx, columns=cols, data=np.array([[0.0, 0.5, 1.0], [1.5, 2.0, -1], [-1, -1, -1]], dtype=float), )
df1[df1 > 2.0 * df2] = -1 tm.assert_frame_equal(df1, expected) with pytest.raises(ValueError, match="Item wrong length"): df1[df1.index[:-1] > 2] = -1
def test_loc_setitem_all_false_boolean_two_blocks(self): # GH#40885 df = DataFrame({"a": [1, 2], "b": [3, 4], "c": "a"}) expected = df.copy() indexer = Series([False, False], name="c") df.loc[indexer, ["b"]] = DataFrame({"b": [5, 6]}, index=[0, 1]) tm.assert_frame_equal(df, expected)
def test_setitem_ea_boolean_mask(self): # GH#47125 df = DataFrame([[-1, 2], [3, -4]]) expected = DataFrame([[0, 2], [3, 0]]) boolean_indexer = DataFrame( { 0: Series([True, False], dtype="boolean"), 1: Series([pd.NA, True], dtype="boolean"), } ) df[boolean_indexer] = 0 tm.assert_frame_equal(df, expected)
class TestDataFrameSetitemCopyViewSemantics: def test_setitem_always_copy(self, float_frame): assert "E" not in float_frame.columns s = float_frame["A"].copy() float_frame["E"] = s
float_frame.iloc[5:10, float_frame.columns.get_loc("E")] = np.nan assert notna(s[5:10]).all()
@pytest.mark.parametrize("consolidate", [True, False]) def test_setitem_partial_column_inplace( self, consolidate, using_array_manager, using_copy_on_write ): # This setting should be in-place, regardless of whether frame is # single-block or multi-block # GH#304 this used to be incorrectly not-inplace, in which case # we needed to ensure _item_cache was cleared.
df = DataFrame( {"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3] ) df.insert(2, "z", np.nan) if not using_array_manager: if consolidate: df._consolidate_inplace() assert len(df._mgr.blocks) == 1 else: assert len(df._mgr.blocks) == 2
zvals = df["z"]._values
df.loc[2:, "z"] = 42
expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z") tm.assert_series_equal(df["z"], expected)
# check setting occurred in-place if not using_copy_on_write: tm.assert_numpy_array_equal(zvals, expected.values) assert np.shares_memory(zvals, df["z"]._values)
def test_setitem_duplicate_columns_not_inplace(self): # GH#39510 cols = ["A", "B"] * 2 df = DataFrame(0.0, index=[0], columns=cols) df_copy = df.copy() df_view = df[:] df["B"] = (2, 5)
expected = DataFrame([[0.0, 2, 0.0, 5]], columns=cols) tm.assert_frame_equal(df_view, df_copy) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( "value", [1, np.array([[1], [1]], dtype="int64"), [[1], [1]]] ) def test_setitem_same_dtype_not_inplace(self, value, using_array_manager): # GH#39510 cols = ["A", "B"] df = DataFrame(0, index=[0, 1], columns=cols) df_copy = df.copy() df_view = df[:] df[["B"]] = value
expected = DataFrame([[0, 1], [0, 1]], columns=cols) tm.assert_frame_equal(df, expected) tm.assert_frame_equal(df_view, df_copy)
@pytest.mark.parametrize("value", [1.0, np.array([[1.0], [1.0]]), [[1.0], [1.0]]]) def test_setitem_listlike_key_scalar_value_not_inplace(self, value): # GH#39510 cols = ["A", "B"] df = DataFrame(0, index=[0, 1], columns=cols) df_copy = df.copy() df_view = df[:] df[["B"]] = value
expected = DataFrame([[0, 1.0], [0, 1.0]], columns=cols) tm.assert_frame_equal(df_view, df_copy) tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( "indexer", [ "a", ["a"], pytest.param( [True, False], marks=pytest.mark.xfail( reason="Boolean indexer incorrectly setting inplace", strict=False, # passing on some builds, no obvious pattern ), ), ], ) @pytest.mark.parametrize( "value, set_value", [ (1, 5), (1.0, 5.0), (Timestamp("2020-12-31"), Timestamp("2021-12-31")), ("a", "b"), ], ) def test_setitem_not_operating_inplace(self, value, set_value, indexer): # GH#43406 df = DataFrame({"a": value}, index=[0, 1]) expected = df.copy() view = df[:] df[indexer] = set_value tm.assert_frame_equal(view, expected)
@td.skip_array_manager_invalid_test def test_setitem_column_update_inplace( self, using_copy_on_write, warn_copy_on_write ): # https://github.com/pandas-dev/pandas/issues/47172
labels = [f"c{i}" for i in range(10)] df = DataFrame({col: np.zeros(len(labels)) for col in labels}, index=labels) values = df._mgr.blocks[0].values
with tm.raises_chained_assignment_error(): for label in df.columns: df[label][label] = 1 if not using_copy_on_write: # diagonal values all updated assert np.all(values[np.arange(10), np.arange(10)] == 1) else: # original dataframe not updated assert np.all(values[np.arange(10), np.arange(10)] == 0)
def test_setitem_column_frame_as_category(self): # GH31581 df = DataFrame([1, 2, 3]) df["col1"] = DataFrame([1, 2, 3], dtype="category") df["col2"] = Series([1, 2, 3], dtype="category")
expected_types = Series( ["int64", "category", "category"], index=[0, "col1", "col2"], dtype=object ) tm.assert_series_equal(df.dtypes, expected_types)
@pytest.mark.parametrize("dtype", ["int64", "Int64"]) def test_setitem_iloc_with_numpy_array(self, dtype): # GH-33828 df = DataFrame({"a": np.ones(3)}, dtype=dtype) df.iloc[np.array([0]), np.array([0])] = np.array([[2]])
expected = DataFrame({"a": [2, 1, 1]}, dtype=dtype) tm.assert_frame_equal(df, expected)
def test_setitem_frame_dup_cols_dtype(self): # GH#53143 df = DataFrame([[1, 2, 3, 4], [4, 5, 6, 7]], columns=["a", "b", "a", "c"]) rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"]) df["a"] = rhs expected = DataFrame( [[0, 2, 1.5, 4], [2, 5, 2.5, 7]], columns=["a", "b", "a", "c"] ) tm.assert_frame_equal(df, expected)
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"]) df["a"] = rhs expected = DataFrame([[0, 1.5, 3], [2, 2.5, 6]], columns=["a", "a", "b"]) tm.assert_frame_equal(df, expected)
def test_frame_setitem_empty_dataframe(self): # GH#28871 dti = DatetimeIndex(["2000-01-01"], dtype="M8[ns]", name="date") df = DataFrame({"date": dti}).set_index("date") df = df[0:0].copy()
df["3010"] = None df["2010"] = None
expected = DataFrame( [], columns=["3010", "2010"], index=dti[:0], ) tm.assert_frame_equal(df, expected)
def test_full_setter_loc_incompatible_dtype(): # https://github.com/pandas-dev/pandas/issues/55791 df = DataFrame({"a": [1, 2]}) with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): df.loc[:, "a"] = True expected = DataFrame({"a": [True, True]}) tm.assert_frame_equal(df, expected)
df = DataFrame({"a": [1, 2]}) with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): df.loc[:, "a"] = {0: 3.5, 1: 4.5} expected = DataFrame({"a": [3.5, 4.5]}) tm.assert_frame_equal(df, expected)
df = DataFrame({"a": [1, 2]}) df.loc[:, "a"] = {0: 3, 1: 4} expected = DataFrame({"a": [3, 4]}) tm.assert_frame_equal(df, expected)
def test_setitem_partial_row_multiple_columns(): # https://github.com/pandas-dev/pandas/issues/56503 df = DataFrame({"A": [1, 2, 3], "B": [4.0, 5, 6]}) # should not warn df.loc[df.index <= 1, ["F", "G"]] = (1, "abc") expected = DataFrame( { "A": [1, 2, 3], "B": [4.0, 5, 6], "F": [1.0, 1, float("nan")], "G": ["abc", "abc", float("nan")], } ) tm.assert_frame_equal(df, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import pytest
import pandas._testing as tm
class TestDataFrameTake: def test_take_slices_deprecated(self, float_frame): # GH#51539 df = float_frame
slc = slice(0, 4, 1) with tm.assert_produces_warning(FutureWarning): df.take(slc, axis=0) with tm.assert_produces_warning(FutureWarning): df.take(slc, axis=1)
def test_take(self, float_frame): # homogeneous order = [3, 1, 2, 0] for df in [float_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected)
# axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["D", "B", "C", "A"]] tm.assert_frame_equal(result, expected, check_names=False)
# negative indices order = [2, 1, -1] for df in [float_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected)
result = df.take(order, axis=0) tm.assert_frame_equal(result, expected)
# axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["C", "B", "D"]] tm.assert_frame_equal(result, expected, check_names=False)
# illegal indices msg = "indices are out-of-bounds" with pytest.raises(IndexError, match=msg): df.take([3, 1, 2, 30], axis=0) with pytest.raises(IndexError, match=msg): df.take([3, 1, 2, -31], axis=0) with pytest.raises(IndexError, match=msg): df.take([3, 1, 2, 5], axis=1) with pytest.raises(IndexError, match=msg): df.take([3, 1, 2, -5], axis=1)
def test_take_mixed_type(self, float_string_frame): # mixed-dtype order = [4, 1, 2, 0, 3] for df in [float_string_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected)
# axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["foo", "B", "C", "A", "D"]] tm.assert_frame_equal(result, expected)
# negative indices order = [4, 1, -2] for df in [float_string_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected)
# axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["foo", "B", "D"]] tm.assert_frame_equal(result, expected)
def test_take_mixed_numeric(self, mixed_float_frame, mixed_int_frame): # by dtype order = [1, 2, 0, 3] for df in [mixed_float_frame, mixed_int_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected)
# axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["B", "C", "A", "D"]] tm.assert_frame_equal(result, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099from datetime import datetime
from hypothesis import givenimport numpy as npimport pytest
from pandas.core.dtypes.common import is_scalar
import pandas as pdfrom pandas import ( DataFrame, DatetimeIndex, Index, Series, StringDtype, Timestamp, date_range, isna,)import pandas._testing as tmfrom pandas._testing._hypothesis import OPTIONAL_ONE_OF_ALL
@pytest.fixture(params=["default", "float_string", "mixed_float", "mixed_int"])def where_frame(request, float_string_frame, mixed_float_frame, mixed_int_frame): if request.param == "default": return DataFrame( np.random.default_rng(2).standard_normal((5, 3)), columns=["A", "B", "C"] ) if request.param == "float_string": return float_string_frame if request.param == "mixed_float": return mixed_float_frame if request.param == "mixed_int": return mixed_int_frame
def _safe_add(df): # only add to the numeric items def is_ok(s): return ( issubclass(s.dtype.type, (np.integer, np.floating)) and s.dtype != "uint8" )
return DataFrame(dict((c, s + 1) if is_ok(s) else (c, s) for c, s in df.items()))
class TestDataFrameIndexingWhere: def test_where_get(self, where_frame, float_string_frame): def _check_get(df, cond, check_dtypes=True): other1 = _safe_add(df) rs = df.where(cond, other1) rs2 = df.where(cond.values, other1) for k, v in rs.items(): exp = Series(np.where(cond[k], df[k], other1[k]), index=v.index) tm.assert_series_equal(v, exp, check_names=False) tm.assert_frame_equal(rs, rs2)
# dtypes if check_dtypes: assert (rs.dtypes == df.dtypes).all()
# check getting df = where_frame if df is float_string_frame: msg = "'>' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): df > 0 return cond = df > 0 _check_get(df, cond)
def test_where_upcasting(self): # upcasting case (GH # 2794) df = DataFrame( { c: Series([1] * 3, dtype=c) for c in ["float32", "float64", "int32", "int64"] } ) df.iloc[1, :] = 0 result = df.dtypes expected = Series( [ np.dtype("float32"), np.dtype("float64"), np.dtype("int32"), np.dtype("int64"), ], index=["float32", "float64", "int32", "int64"], )
# when we don't preserve boolean casts # # expected = Series({ 'float32' : 1, 'float64' : 3 })
tm.assert_series_equal(result, expected)
@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") def test_where_alignment(self, where_frame, float_string_frame): # aligning def _check_align(df, cond, other, check_dtypes=True): rs = df.where(cond, other) for i, k in enumerate(rs.columns): result = rs[k] d = df[k].values c = cond[k].reindex(df[k].index).fillna(False).values
if is_scalar(other): o = other elif isinstance(other, np.ndarray): o = Series(other[:, i], index=result.index).values else: o = other[k].values
new_values = d if c.all() else np.where(c, d, o) expected = Series(new_values, index=result.index, name=k)
# since we can't always have the correct numpy dtype # as numpy doesn't know how to downcast, don't check tm.assert_series_equal(result, expected, check_dtype=False)
# dtypes # can't check dtype when other is an ndarray
if check_dtypes and not isinstance(other, np.ndarray): assert (rs.dtypes == df.dtypes).all()
df = where_frame if df is float_string_frame: msg = "'>' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): df > 0 return
# other is a frame cond = (df > 0)[1:] _check_align(df, cond, _safe_add(df))
# check other is ndarray cond = df > 0 _check_align(df, cond, (_safe_add(df).values))
# integers are upcast, so don't check the dtypes cond = df > 0 check_dtypes = all(not issubclass(s.type, np.integer) for s in df.dtypes) _check_align(df, cond, np.nan, check_dtypes=check_dtypes)
# Ignore deprecation warning in Python 3.12 for inverting a bool @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_where_invalid(self): # invalid conditions df = DataFrame( np.random.default_rng(2).standard_normal((5, 3)), columns=["A", "B", "C"] ) cond = df > 0
err1 = (df + 1).values[0:2, :] msg = "other must be the same shape as self when an ndarray" with pytest.raises(ValueError, match=msg): df.where(cond, err1)
err2 = cond.iloc[:2, :].values other1 = _safe_add(df) msg = "Array conditional must be same shape as self" with pytest.raises(ValueError, match=msg): df.where(err2, other1)
with pytest.raises(ValueError, match=msg): df.mask(True) with pytest.raises(ValueError, match=msg): df.mask(0)
@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") def test_where_set(self, where_frame, float_string_frame, mixed_int_frame): # where inplace
def _check_set(df, cond, check_dtypes=True): dfi = df.copy() econd = cond.reindex_like(df).fillna(True).infer_objects(copy=False) expected = dfi.mask(~econd)
return_value = dfi.where(cond, np.nan, inplace=True) assert return_value is None tm.assert_frame_equal(dfi, expected)
# dtypes (and confirm upcasts)x if check_dtypes: for k, v in df.dtypes.items(): if issubclass(v.type, np.integer) and not cond[k].all(): v = np.dtype("float64") assert dfi[k].dtype == v
df = where_frame if df is float_string_frame: msg = "'>' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): df > 0 return if df is mixed_int_frame: df = df.astype("float64")
cond = df > 0 _check_set(df, cond)
cond = df >= 0 _check_set(df, cond)
# aligning cond = (df >= 0)[1:] _check_set(df, cond)
def test_where_series_slicing(self): # GH 10218 # test DataFrame.where with Series slicing df = DataFrame({"a": range(3), "b": range(4, 7)}) result = df.where(df["a"] == 1) expected = df[df["a"] == 1].reindex(df.index) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("klass", [list, tuple, np.array]) def test_where_array_like(self, klass): # see gh-15414 df = DataFrame({"a": [1, 2, 3]}) cond = [[False], [True], [True]] expected = DataFrame({"a": [np.nan, 2, 3]})
result = df.where(klass(cond)) tm.assert_frame_equal(result, expected)
df["b"] = 2 expected["b"] = [2, np.nan, 2] cond = [[False, True], [True, False], [True, True]]
result = df.where(klass(cond)) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( "cond", [ [[1], [0], [1]], Series([[2], [5], [7]]), DataFrame({"a": [2, 5, 7]}), [["True"], ["False"], ["True"]], [[Timestamp("2017-01-01")], [pd.NaT], [Timestamp("2017-01-02")]], ], ) def test_where_invalid_input_single(self, cond): # see gh-15414: only boolean arrays accepted df = DataFrame({"a": [1, 2, 3]}) msg = "Boolean array expected for the condition"
with pytest.raises(ValueError, match=msg): df.where(cond)
@pytest.mark.parametrize( "cond", [ [[0, 1], [1, 0], [1, 1]], Series([[0, 2], [5, 0], [4, 7]]), [["False", "True"], ["True", "False"], ["True", "True"]], DataFrame({"a": [2, 5, 7], "b": [4, 8, 9]}), [ [pd.NaT, Timestamp("2017-01-01")], [Timestamp("2017-01-02"), pd.NaT], [Timestamp("2017-01-03"), Timestamp("2017-01-03")], ], ], ) def test_where_invalid_input_multiple(self, cond): # see gh-15414: only boolean arrays accepted df = DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]}) msg = "Boolean array expected for the condition"
with pytest.raises(ValueError, match=msg): df.where(cond)
def test_where_dataframe_col_match(self): df = DataFrame([[1, 2, 3], [4, 5, 6]]) cond = DataFrame([[True, False, True], [False, False, True]])
result = df.where(cond) expected = DataFrame([[1.0, np.nan, 3], [np.nan, np.nan, 6]]) tm.assert_frame_equal(result, expected)
# this *does* align, though has no matching columns cond.columns = ["a", "b", "c"] result = df.where(cond) expected = DataFrame(np.nan, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected)
def test_where_ndframe_align(self): msg = "Array conditional must be same shape as self" df = DataFrame([[1, 2, 3], [4, 5, 6]])
cond = [True] with pytest.raises(ValueError, match=msg): df.where(cond)
expected = DataFrame([[1, 2, 3], [np.nan, np.nan, np.nan]])
out = df.where(Series(cond)) tm.assert_frame_equal(out, expected)
cond = np.array([False, True, False, True]) with pytest.raises(ValueError, match=msg): df.where(cond)
expected = DataFrame([[np.nan, np.nan, np.nan], [4, 5, 6]])
out = df.where(Series(cond)) tm.assert_frame_equal(out, expected)
def test_where_bug(self): # see gh-2793 df = DataFrame( {"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]}, dtype="float64" ) expected = DataFrame( {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]}, dtype="float64", ) result = df.where(df > 2, np.nan) tm.assert_frame_equal(result, expected)
result = df.copy() return_value = result.where(result > 2, np.nan, inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
def test_where_bug_mixed(self, any_signed_int_numpy_dtype): # see gh-2793 df = DataFrame( { "a": np.array([1, 2, 3, 4], dtype=any_signed_int_numpy_dtype), "b": np.array([4.0, 3.0, 2.0, 1.0], dtype="float64"), } )
expected = DataFrame( {"a": [-1, -1, 3, 4], "b": [4.0, 3.0, -1, -1]}, ).astype({"a": any_signed_int_numpy_dtype, "b": "float64"})
result = df.where(df > 2, -1) tm.assert_frame_equal(result, expected)
result = df.copy() return_value = result.where(result > 2, -1, inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
def test_where_bug_transposition(self): # see gh-7506 a = DataFrame({0: [1, 2], 1: [3, 4], 2: [5, 6]}) b = DataFrame({0: [np.nan, 8], 1: [9, np.nan], 2: [np.nan, np.nan]}) do_not_replace = b.isna() | (a > b)
expected = a.copy() expected[~do_not_replace] = b
msg = "Downcasting behavior in Series and DataFrame methods 'where'" with tm.assert_produces_warning(FutureWarning, match=msg): result = a.where(do_not_replace, b) tm.assert_frame_equal(result, expected)
a = DataFrame({0: [4, 6], 1: [1, 0]}) b = DataFrame({0: [np.nan, 3], 1: [3, np.nan]}) do_not_replace = b.isna() | (a > b)
expected = a.copy() expected[~do_not_replace] = b
with tm.assert_produces_warning(FutureWarning, match=msg): result = a.where(do_not_replace, b) tm.assert_frame_equal(result, expected)
def test_where_datetime(self): # GH 3311 df = DataFrame( { "A": date_range("20130102", periods=5), "B": date_range("20130104", periods=5), "C": np.random.default_rng(2).standard_normal(5), } )
stamp = datetime(2013, 1, 3) msg = "'>' not supported between instances of 'float' and 'datetime.datetime'" with pytest.raises(TypeError, match=msg): df > stamp
result = df[df.iloc[:, :-1] > stamp]
expected = df.copy() expected.loc[[0, 1], "A"] = np.nan
expected.loc[:, "C"] = np.nan tm.assert_frame_equal(result, expected)
def test_where_none(self): # GH 4667 # setting with None changes dtype df = DataFrame({"series": Series(range(10))}).astype(float) df[df > 7] = None expected = DataFrame( {"series": Series([0, 1, 2, 3, 4, 5, 6, 7, np.nan, np.nan])} ) tm.assert_frame_equal(df, expected)
# GH 7656 df = DataFrame( [ {"A": 1, "B": np.nan, "C": "Test"}, {"A": np.nan, "B": "Test", "C": np.nan}, ] )
orig = df.copy()
mask = ~isna(df) df.where(mask, None, inplace=True) expected = DataFrame( { "A": [1.0, np.nan], "B": [None, "Test"], "C": ["Test", None], } ) tm.assert_frame_equal(df, expected)
df = orig.copy() df[~mask] = None tm.assert_frame_equal(df, expected)
def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self): # see gh-21947 df = DataFrame(columns=["a"]) cond = df assert (cond.dtypes == object).all()
result = df.where(cond) tm.assert_frame_equal(result, df)
def test_where_align(self): def create(): df = DataFrame(np.random.default_rng(2).standard_normal((10, 3))) df.iloc[3:5, 0] = np.nan df.iloc[4:6, 1] = np.nan df.iloc[5:8, 2] = np.nan return df
# series df = create() expected = df.fillna(df.mean()) result = df.where(pd.notna(df), df.mean(), axis="columns") tm.assert_frame_equal(result, expected)
return_value = df.where(pd.notna(df), df.mean(), inplace=True, axis="columns") assert return_value is None tm.assert_frame_equal(df, expected)
df = create().fillna(0) expected = df.apply(lambda x, y: x.where(x > 0, y), y=df[0]) result = df.where(df > 0, df[0], axis="index") tm.assert_frame_equal(result, expected) result = df.where(df > 0, df[0], axis="rows") tm.assert_frame_equal(result, expected)
# frame df = create() expected = df.fillna(1) result = df.where( pd.notna(df), DataFrame(1, index=df.index, columns=df.columns) ) tm.assert_frame_equal(result, expected)
def test_where_complex(self): # GH 6345 expected = DataFrame([[1 + 1j, 2], [np.nan, 4 + 1j]], columns=["a", "b"]) df = DataFrame([[1 + 1j, 2], [5 + 1j, 4 + 1j]], columns=["a", "b"]) df[df.abs() >= 5] = np.nan tm.assert_frame_equal(df, expected)
def test_where_axis(self): # GH 9736 df = DataFrame(np.random.default_rng(2).standard_normal((2, 2))) mask = DataFrame([[False, False], [False, False]]) ser = Series([0, 1])
expected = DataFrame([[0, 0], [1, 1]], dtype="float64") result = df.where(mask, ser, axis="index") tm.assert_frame_equal(result, expected)
result = df.copy() return_value = result.where(mask, ser, axis="index", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
expected = DataFrame([[0, 1], [0, 1]], dtype="float64") result = df.where(mask, ser, axis="columns") tm.assert_frame_equal(result, expected)
result = df.copy() return_value = result.where(mask, ser, axis="columns", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
def test_where_axis_with_upcast(self): # Upcast needed df = DataFrame([[1, 2], [3, 4]], dtype="int64") mask = DataFrame([[False, False], [False, False]]) ser = Series([0, np.nan])
expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64") result = df.where(mask, ser, axis="index") tm.assert_frame_equal(result, expected)
result = df.copy() with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): return_value = result.where(mask, ser, axis="index", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
expected = DataFrame([[0, np.nan], [0, np.nan]]) result = df.where(mask, ser, axis="columns") tm.assert_frame_equal(result, expected)
expected = DataFrame( { 0: np.array([0, 0], dtype="int64"), 1: np.array([np.nan, np.nan], dtype="float64"), } ) result = df.copy() with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): return_value = result.where(mask, ser, axis="columns", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
def test_where_axis_multiple_dtypes(self): # Multiple dtypes (=> multiple Blocks) df = pd.concat( [ DataFrame(np.random.default_rng(2).standard_normal((10, 2))), DataFrame( np.random.default_rng(2).integers(0, 10, size=(10, 2)), dtype="int64", ), ], ignore_index=True, axis=1, ) mask = DataFrame(False, columns=df.columns, index=df.index) s1 = Series(1, index=df.columns) s2 = Series(2, index=df.index)
result = df.where(mask, s1, axis="columns") expected = DataFrame(1.0, columns=df.columns, index=df.index) expected[2] = expected[2].astype("int64") expected[3] = expected[3].astype("int64") tm.assert_frame_equal(result, expected)
result = df.copy() return_value = result.where(mask, s1, axis="columns", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
result = df.where(mask, s2, axis="index") expected = DataFrame(2.0, columns=df.columns, index=df.index) expected[2] = expected[2].astype("int64") expected[3] = expected[3].astype("int64") tm.assert_frame_equal(result, expected)
result = df.copy() return_value = result.where(mask, s2, axis="index", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected)
# DataFrame vs DataFrame d1 = df.copy().drop(1, axis=0) # Explicit cast to avoid implicit cast when setting value to np.nan expected = df.copy().astype("float") expected.loc[1, :] = np.nan
result = df.where(mask, d1) tm.assert_frame_equal(result, expected) result = df.where(mask, d1, axis="index") tm.assert_frame_equal(result, expected) result = df.copy() with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): return_value = result.where(mask, d1, inplace=True) assert return_value is None tm.assert_frame_equal(result, expected) result = df.copy() with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): return_value = result.where(mask, d1, inplace=True, axis="index") assert return_value is None tm.assert_frame_equal(result, expected)
d2 = df.copy().drop(1, axis=1) expected = df.copy() expected.loc[:, 1] = np.nan
result = df.where(mask, d2) tm.assert_frame_equal(result, expected) result = df.where(mask, d2, axis="columns") tm.assert_frame_equal(result, expected) result = df.copy() return_value = result.where(mask, d2, inplace=True) assert return_value is None tm.assert_frame_equal(result, expected) result = df.copy() return_value = result.where(mask, d2, inplace=True, axis="columns") assert return_value is None tm.assert_frame_equal(result, expected)
def test_where_callable(self): # GH 12533 df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) result = df.where(lambda x: x > 4, lambda x: x + 1) exp = DataFrame([[2, 3, 4], [5, 5, 6], [7, 8, 9]]) tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, df.where(df > 4, df + 1))
# return ndarray and scalar result = df.where(lambda x: (x % 2 == 0).values, lambda x: 99) exp = DataFrame([[99, 2, 99], [4, 99, 6], [99, 8, 99]]) tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, df.where(df % 2 == 0, 99))
# chain result = (df + 2).where(lambda x: x > 8, lambda x: x + 10) exp = DataFrame([[13, 14, 15], [16, 17, 18], [9, 10, 11]]) tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10))
def test_where_tz_values(self, tz_naive_fixture, frame_or_series): obj1 = DataFrame( DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture), columns=["date"], ) obj2 = DataFrame( DatetimeIndex(["20150103", "20150104", "20150105"], tz=tz_naive_fixture), columns=["date"], ) mask = DataFrame([True, True, False], columns=["date"]) exp = DataFrame( DatetimeIndex(["20150101", "20150102", "20150105"], tz=tz_naive_fixture), columns=["date"], ) if frame_or_series is Series: obj1 = obj1["date"] obj2 = obj2["date"] mask = mask["date"] exp = exp["date"]
result = obj1.where(mask, obj2) tm.assert_equal(exp, result)
def test_df_where_change_dtype(self): # GH#16979 df = DataFrame(np.arange(2 * 3).reshape(2, 3), columns=list("ABC")) mask = np.array([[True, False, False], [False, False, True]])
result = df.where(mask) expected = DataFrame( [[0, np.nan, np.nan], [np.nan, np.nan, 5]], columns=list("ABC") )
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("kwargs", [{}, {"other": None}]) def test_df_where_with_category(self, kwargs): # GH#16979 data = np.arange(2 * 3, dtype=np.int64).reshape(2, 3) df = DataFrame(data, columns=list("ABC")) mask = np.array([[True, False, False], [False, False, True]])
# change type to category df.A = df.A.astype("category") df.B = df.B.astype("category") df.C = df.C.astype("category")
result = df.where(mask, **kwargs) A = pd.Categorical([0, np.nan], categories=[0, 3]) B = pd.Categorical([np.nan, np.nan], categories=[1, 4]) C = pd.Categorical([np.nan, 5], categories=[2, 5]) expected = DataFrame({"A": A, "B": B, "C": C})
tm.assert_frame_equal(result, expected)
# Check Series.where while we're here result = df.A.where(mask[:, 0], **kwargs) expected = Series(A, name="A")
tm.assert_series_equal(result, expected)
def test_where_categorical_filtering(self): # GH#22609 Verify filtering operations on DataFrames with categorical Series df = DataFrame(data=[[0, 0], [1, 1]], columns=["a", "b"]) df["b"] = df["b"].astype("category")
result = df.where(df["a"] > 0) # Explicitly cast to 'float' to avoid implicit cast when setting np.nan expected = df.copy().astype({"a": "float"}) expected.loc[0, :] = np.nan
tm.assert_equal(result, expected)
def test_where_ea_other(self): # GH#38729/GH#38742 df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) arr = pd.array([7, pd.NA, 9]) ser = Series(arr) mask = np.ones(df.shape, dtype=bool) mask[1, :] = False
# TODO: ideally we would get Int64 instead of object result = df.where(mask, ser, axis=0) expected = DataFrame({"A": [1, np.nan, 3], "B": [4, np.nan, 6]}) tm.assert_frame_equal(result, expected)
ser2 = Series(arr[:2], index=["A", "B"]) expected = DataFrame({"A": [1, 7, 3], "B": [4, np.nan, 6]}) result = df.where(mask, ser2, axis=1) tm.assert_frame_equal(result, expected)
def test_where_interval_noop(self): # GH#44181 df = DataFrame([pd.Interval(0, 0)]) res = df.where(df.notna()) tm.assert_frame_equal(res, df)
ser = df[0] res = ser.where(ser.notna()) tm.assert_series_equal(res, ser)
def test_where_interval_fullop_downcast(self, frame_or_series): # GH#45768 obj = frame_or_series([pd.Interval(0, 0)] * 2) other = frame_or_series([1.0, 2.0])
msg = "Downcasting behavior in Series and DataFrame methods 'where'" with tm.assert_produces_warning(FutureWarning, match=msg): res = obj.where(~obj.notna(), other)
# since all entries are being changed, we will downcast result # from object to ints (not floats) tm.assert_equal(res, other.astype(np.int64))
# unlike where, Block.putmask does not downcast with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): obj.mask(obj.notna(), other, inplace=True) tm.assert_equal(obj, other.astype(object))
@pytest.mark.parametrize( "dtype", [ "timedelta64[ns]", "datetime64[ns]", "datetime64[ns, Asia/Tokyo]", "Period[D]", ], ) def test_where_datetimelike_noop(self, dtype): # GH#45135, analogue to GH#44181 for Period don't raise on no-op # For td64/dt64/dt64tz we already don't raise, but also are # checking that we don't unnecessarily upcast to object. with tm.assert_produces_warning(FutureWarning, match="is deprecated"): ser = Series(np.arange(3) * 10**9, dtype=np.int64).view(dtype) df = ser.to_frame() mask = np.array([False, False, False])
res = ser.where(~mask, "foo") tm.assert_series_equal(res, ser)
mask2 = mask.reshape(-1, 1) res2 = df.where(~mask2, "foo") tm.assert_frame_equal(res2, df)
res3 = ser.mask(mask, "foo") tm.assert_series_equal(res3, ser)
res4 = df.mask(mask2, "foo") tm.assert_frame_equal(res4, df)
# opposite case where we are replacing *all* values -> we downcast # from object dtype # GH#45768 msg = "Downcasting behavior in Series and DataFrame methods 'where'" with tm.assert_produces_warning(FutureWarning, match=msg): res5 = df.where(mask2, 4) expected = DataFrame(4, index=df.index, columns=df.columns) tm.assert_frame_equal(res5, expected)
# unlike where, Block.putmask does not downcast with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): df.mask(~mask2, 4, inplace=True) tm.assert_frame_equal(df, expected.astype(object))
def test_where_int_downcasting_deprecated(): # GH#44597 arr = np.arange(6).astype(np.int16).reshape(3, 2) df = DataFrame(arr)
mask = np.zeros(arr.shape, dtype=bool) mask[:, 0] = True
res = df.where(mask, 2**17)
expected = DataFrame({0: arr[:, 0], 1: np.array([2**17] * 3, dtype=np.int32)}) tm.assert_frame_equal(res, expected)
def test_where_copies_with_noop(frame_or_series): # GH-39595 result = frame_or_series([1, 2, 3, 4]) expected = result.copy() col = result[0] if frame_or_series is DataFrame else result
where_res = result.where(col < 5) where_res *= 2
tm.assert_equal(result, expected)
where_res = result.where(col > 5, [1, 2, 3, 4]) where_res *= 2
tm.assert_equal(result, expected)
def test_where_string_dtype(frame_or_series): # GH40824 obj = frame_or_series( ["a", "b", "c", "d"], index=["id1", "id2", "id3", "id4"], dtype=StringDtype() ) filtered_obj = frame_or_series( ["b", "c"], index=["id2", "id3"], dtype=StringDtype() ) filter_ser = Series([False, True, True, False])
result = obj.where(filter_ser, filtered_obj) expected = frame_or_series( [pd.NA, "b", "c", pd.NA], index=["id1", "id2", "id3", "id4"], dtype=StringDtype(), ) tm.assert_equal(result, expected)
result = obj.mask(~filter_ser, filtered_obj) tm.assert_equal(result, expected)
obj.mask(~filter_ser, filtered_obj, inplace=True) tm.assert_equal(result, expected)
def test_where_bool_comparison(): # GH 10336 df_mask = DataFrame( {"AAA": [True] * 4, "BBB": [False] * 4, "CCC": [True, False, True, False]} ) result = df_mask.where(df_mask == False) # noqa: E712 expected = DataFrame( { "AAA": np.array([np.nan] * 4, dtype=object), "BBB": [False] * 4, "CCC": [np.nan, False, np.nan, False], } ) tm.assert_frame_equal(result, expected)
def test_where_none_nan_coerce(): # GH 15613 expected = DataFrame( { "A": [Timestamp("20130101"), pd.NaT, Timestamp("20130103")], "B": [1, 2, np.nan], } ) result = expected.where(expected.notnull(), None) tm.assert_frame_equal(result, expected)
def test_where_duplicate_axes_mixed_dtypes(): # GH 25399, verify manually masking is not affected anymore by dtype of column for # duplicate axes. result = DataFrame(data=[[0, np.nan]], columns=Index(["A", "A"])) index, columns = result.axes mask = DataFrame(data=[[True, True]], columns=columns, index=index) a = result.astype(object).where(mask) b = result.astype("f8").where(mask) c = result.T.where(mask.T).T d = result.where(mask) # used to fail with "cannot reindex from a duplicate axis" tm.assert_frame_equal(a.astype("f8"), b.astype("f8")) tm.assert_frame_equal(b.astype("f8"), c.astype("f8")) tm.assert_frame_equal(c.astype("f8"), d.astype("f8"))
def test_where_columns_casting(): # GH 42295
df = DataFrame({"a": [1.0, 2.0], "b": [3, np.nan]}) expected = df.copy() result = df.where(pd.notnull(df), None) # make sure dtypes don't change tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("as_cat", [True, False])def test_where_period_invalid_na(frame_or_series, as_cat, request): # GH#44697 idx = pd.period_range("2016-01-01", periods=3, freq="D") if as_cat: idx = idx.astype("category") obj = frame_or_series(idx)
# NA value that we should *not* cast to Period dtype tdnat = pd.NaT.to_numpy("m8[ns]")
mask = np.array([True, True, False], ndmin=obj.ndim).T
if as_cat: msg = ( r"Cannot setitem on a Categorical with a new category \(NaT\), " "set the categories first" ) else: msg = "value should be a 'Period'"
if as_cat: with pytest.raises(TypeError, match=msg): obj.where(mask, tdnat)
with pytest.raises(TypeError, match=msg): obj.mask(mask, tdnat)
with pytest.raises(TypeError, match=msg): obj.mask(mask, tdnat, inplace=True)
else: # With PeriodDtype, ser[i] = tdnat coerces instead of raising, # so for consistency, ser[mask] = tdnat must as well expected = obj.astype(object).where(mask, tdnat) result = obj.where(mask, tdnat) tm.assert_equal(result, expected)
expected = obj.astype(object).mask(mask, tdnat) result = obj.mask(mask, tdnat) tm.assert_equal(result, expected)
with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): obj.mask(mask, tdnat, inplace=True) tm.assert_equal(obj, expected)
def test_where_nullable_invalid_na(frame_or_series, any_numeric_ea_dtype): # GH#44697 arr = pd.array([1, 2, 3], dtype=any_numeric_ea_dtype) obj = frame_or_series(arr)
mask = np.array([True, True, False], ndmin=obj.ndim).T
msg = r"Invalid value '.*' for dtype (U?Int|Float)\d{1,2}"
for null in tm.NP_NAT_OBJECTS + [pd.NaT]: # NaT is an NA value that we should *not* cast to pd.NA dtype with pytest.raises(TypeError, match=msg): obj.where(mask, null)
with pytest.raises(TypeError, match=msg): obj.mask(mask, null)
@given(data=OPTIONAL_ONE_OF_ALL)def test_where_inplace_casting(data): # GH 22051 df = DataFrame({"a": data}) df_copy = df.where(pd.notnull(df), None).copy() df.where(pd.notnull(df), None, inplace=True) tm.assert_equal(df, df_copy)
def test_where_downcast_to_td64(): ser = Series([1, 2, 3])
mask = np.array([False, False, False])
td = pd.Timedelta(days=1)
msg = "Downcasting behavior in Series and DataFrame methods 'where'" with tm.assert_produces_warning(FutureWarning, match=msg): res = ser.where(mask, td) expected = Series([td, td, td], dtype="m8[ns]") tm.assert_series_equal(res, expected)
with pd.option_context("future.no_silent_downcasting", True): with tm.assert_produces_warning(None, match=msg): res2 = ser.where(mask, td) expected2 = expected.astype(object) tm.assert_series_equal(res2, expected2)
def _check_where_equivalences(df, mask, other, expected): # similar to tests.series.indexing.test_setitem.SetitemCastingEquivalences # but with DataFrame in mind and less fleshed-out res = df.where(mask, other) tm.assert_frame_equal(res, expected)
res = df.mask(~mask, other) tm.assert_frame_equal(res, expected)
# Note: frame.mask(~mask, other, inplace=True) takes some more work bc # Block.putmask does *not* downcast. The change to 'expected' here # is specific to the cases in test_where_dt64_2d. df = df.copy() df.mask(~mask, other, inplace=True) if not mask.all(): # with mask.all(), Block.putmask is a no-op, so does not downcast expected = expected.copy() expected["A"] = expected["A"].astype(object) tm.assert_frame_equal(df, expected)
def test_where_dt64_2d(): dti = date_range("2016-01-01", periods=6) dta = dti._data.reshape(3, 2) other = dta - dta[0, 0]
df = DataFrame(dta, columns=["A", "B"])
mask = np.asarray(df.isna()).copy() mask[:, 1] = True
# setting all of one column, none of the other expected = DataFrame({"A": other[:, 0], "B": dta[:, 1]}) with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): _check_where_equivalences(df, mask, other, expected)
# setting part of one column, none of the other mask[1, 0] = True expected = DataFrame( { "A": np.array([other[0, 0], dta[1, 0], other[2, 0]], dtype=object), "B": dta[:, 1], } ) with tm.assert_produces_warning( FutureWarning, match="Setting an item of incompatible dtype" ): _check_where_equivalences(df, mask, other, expected)
# setting nothing in either column mask[:] = True expected = df _check_where_equivalences(df, mask, other, expected)
def test_where_producing_ea_cond_for_np_dtype(): # GH#44014 df = DataFrame({"a": Series([1, pd.NA, 2], dtype="Int64"), "b": [1, 2, 3]}) result = df.where(lambda x: x.apply(lambda y: y > 1, axis=1)) expected = DataFrame( {"a": Series([pd.NA, pd.NA, 2], dtype="Int64"), "b": [np.nan, 2, 3]} ) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( "replacement", [0.001, True, "snake", None, datetime(2022, 5, 4)])def test_where_int_overflow(replacement, using_infer_string, request): # GH 31687 df = DataFrame([[1.0, 2e25, "nine"], [np.nan, 0.1, None]]) if using_infer_string and replacement not in (None, "snake"): request.node.add_marker( pytest.mark.xfail(reason="Can't set non-string into string column") ) result = df.where(pd.notnull(df), replacement) expected = DataFrame([[1.0, 2e25, "nine"], [replacement, 0.1, replacement]])
tm.assert_frame_equal(result, expected)
def test_where_inplace_no_other(): # GH#51685 df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]}) cond = DataFrame({"a": [True, False], "b": [False, True]}) df.where(cond, inplace=True) expected = DataFrame({"a": [1, np.nan], "b": [np.nan, "y"]}) tm.assert_frame_equal(df, expected)lib/python3.12/site-packages/pandas/tests/frame/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/common.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/conftest.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_alter_axes.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_api.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_arrow_interface.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_block_internals.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_cumulative.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_iteration.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_logical_ops.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_nonunique_indexes.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_npfuncs.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_query_eval.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_repr.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_subclass.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_ufunc.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_unary.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_validate.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/constructors/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/frame/constructors/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_dict.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/constructors/__pycache__/test_from_records.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/constructors/test_from_dict.pyAdded+228
lib/python3.12/site-packages/pandas/tests/frame/constructors/test_from_records.pyAdded+505
lib/python3.12/site-packages/pandas/tests/frame/indexing/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_coercion.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_delitem.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_get.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_get_value.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_getitem.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_insert.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_mask.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_set_value.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_setitem.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_take.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_where.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_xs.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_coercion.pyAdded+199
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_delitem.pyAdded+60
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_get.pyAdded+27
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_get_value.pyAdded+22
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_getitem.pyAdded+472
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_indexing.pyAdded+2024
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_insert.pyAdded+120
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_mask.pyAdded+152
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_set_value.pyAdded+77
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_setitem.pyAdded+1419
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_take.pyAdded+92
lib/python3.12/site-packages/pandas/tests/frame/indexing/test_where.pyAdded+1099