test_setitem.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import numpy as np
  2. import pytest
  3. from pandas.errors import SettingWithCopyError
  4. import pandas.util._test_decorators as td
  5. import pandas as pd
  6. from pandas import (
  7. DataFrame,
  8. MultiIndex,
  9. Series,
  10. Timestamp,
  11. date_range,
  12. isna,
  13. notna,
  14. )
  15. import pandas._testing as tm
  16. def assert_equal(a, b):
  17. assert a == b
  18. class TestMultiIndexSetItem:
  19. def check(self, target, indexers, value, compare_fn=assert_equal, expected=None):
  20. target.loc[indexers] = value
  21. result = target.loc[indexers]
  22. if expected is None:
  23. expected = value
  24. compare_fn(result, expected)
  25. def test_setitem_multiindex(self):
  26. # GH#7190
  27. cols = ["A", "w", "l", "a", "x", "X", "d", "profit"]
  28. index = MultiIndex.from_product(
  29. [np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"]
  30. )
  31. t, n = 0, 2
  32. df = DataFrame(
  33. np.nan,
  34. columns=cols,
  35. index=index,
  36. )
  37. self.check(target=df, indexers=((t, n), "X"), value=0)
  38. df = DataFrame(-999, columns=cols, index=index)
  39. self.check(target=df, indexers=((t, n), "X"), value=1)
  40. df = DataFrame(columns=cols, index=index)
  41. self.check(target=df, indexers=((t, n), "X"), value=2)
  42. # gh-7218: assigning with 0-dim arrays
  43. df = DataFrame(-999, columns=cols, index=index)
  44. self.check(
  45. target=df,
  46. indexers=((t, n), "X"),
  47. value=np.array(3),
  48. expected=3,
  49. )
  50. def test_setitem_multiindex2(self):
  51. # GH#5206
  52. df = DataFrame(
  53. np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float
  54. )
  55. df["F"] = 99
  56. row_selection = df["A"] % 2 == 0
  57. col_selection = ["B", "C"]
  58. df.loc[row_selection, col_selection] = df["F"]
  59. output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"])
  60. tm.assert_frame_equal(df.loc[row_selection, col_selection], output)
  61. self.check(
  62. target=df,
  63. indexers=(row_selection, col_selection),
  64. value=df["F"],
  65. compare_fn=tm.assert_frame_equal,
  66. expected=output,
  67. )
  68. def test_setitem_multiindex3(self):
  69. # GH#11372
  70. idx = MultiIndex.from_product(
  71. [["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")]
  72. )
  73. cols = MultiIndex.from_product(
  74. [["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")]
  75. )
  76. df = DataFrame(np.random.random((12, 4)), index=idx, columns=cols)
  77. subidx = MultiIndex.from_tuples(
  78. [("A", Timestamp("2015-01-01")), ("A", Timestamp("2015-02-01"))]
  79. )
  80. subcols = MultiIndex.from_tuples(
  81. [("foo", Timestamp("2016-01-01")), ("foo", Timestamp("2016-02-01"))]
  82. )
  83. vals = DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols)
  84. self.check(
  85. target=df,
  86. indexers=(subidx, subcols),
  87. value=vals,
  88. compare_fn=tm.assert_frame_equal,
  89. )
  90. # set all columns
  91. vals = DataFrame(np.random.random((2, 4)), index=subidx, columns=cols)
  92. self.check(
  93. target=df,
  94. indexers=(subidx, slice(None, None, None)),
  95. value=vals,
  96. compare_fn=tm.assert_frame_equal,
  97. )
  98. # identity
  99. copy = df.copy()
  100. self.check(
  101. target=df,
  102. indexers=(df.index, df.columns),
  103. value=df,
  104. compare_fn=tm.assert_frame_equal,
  105. expected=copy,
  106. )
  107. # TODO(ArrayManager) df.loc["bar"] *= 2 doesn't raise an error but results in
  108. # all NaNs -> doesn't work in the "split" path (also for BlockManager actually)
  109. @td.skip_array_manager_not_yet_implemented
  110. def test_multiindex_setitem(self):
  111. # GH 3738
  112. # setting with a multi-index right hand side
  113. arrays = [
  114. np.array(["bar", "bar", "baz", "qux", "qux", "bar"]),
  115. np.array(["one", "two", "one", "one", "two", "one"]),
  116. np.arange(0, 6, 1),
  117. ]
  118. df_orig = DataFrame(
  119. np.random.randn(6, 3), index=arrays, columns=["A", "B", "C"]
  120. ).sort_index()
  121. expected = df_orig.loc[["bar"]] * 2
  122. df = df_orig.copy()
  123. df.loc[["bar"]] *= 2
  124. tm.assert_frame_equal(df.loc[["bar"]], expected)
  125. # raise because these have differing levels
  126. msg = "cannot align on a multi-index with out specifying the join levels"
  127. with pytest.raises(TypeError, match=msg):
  128. df.loc["bar"] *= 2
  129. def test_multiindex_setitem2(self):
  130. # from SO
  131. # https://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation
  132. df_orig = DataFrame.from_dict(
  133. {
  134. "price": {
  135. ("DE", "Coal", "Stock"): 2,
  136. ("DE", "Gas", "Stock"): 4,
  137. ("DE", "Elec", "Demand"): 1,
  138. ("FR", "Gas", "Stock"): 5,
  139. ("FR", "Solar", "SupIm"): 0,
  140. ("FR", "Wind", "SupIm"): 0,
  141. }
  142. }
  143. )
  144. df_orig.index = MultiIndex.from_tuples(
  145. df_orig.index, names=["Sit", "Com", "Type"]
  146. )
  147. expected = df_orig.copy()
  148. expected.iloc[[0, 2, 3]] *= 2
  149. idx = pd.IndexSlice
  150. df = df_orig.copy()
  151. df.loc[idx[:, :, "Stock"], :] *= 2
  152. tm.assert_frame_equal(df, expected)
  153. df = df_orig.copy()
  154. df.loc[idx[:, :, "Stock"], "price"] *= 2
  155. tm.assert_frame_equal(df, expected)
  156. def test_multiindex_assignment(self):
  157. # GH3777 part 2
  158. # mixed dtype
  159. df = DataFrame(
  160. np.random.randint(5, 10, size=9).reshape(3, 3),
  161. columns=list("abc"),
  162. index=[[4, 4, 8], [8, 10, 12]],
  163. )
  164. df["d"] = np.nan
  165. arr = np.array([0.0, 1.0])
  166. df.loc[4, "d"] = arr
  167. tm.assert_series_equal(df.loc[4, "d"], Series(arr, index=[8, 10], name="d"))
  168. def test_multiindex_assignment_single_dtype(self, using_copy_on_write):
  169. # GH3777 part 2b
  170. # single dtype
  171. arr = np.array([0.0, 1.0])
  172. df = DataFrame(
  173. np.random.randint(5, 10, size=9).reshape(3, 3),
  174. columns=list("abc"),
  175. index=[[4, 4, 8], [8, 10, 12]],
  176. dtype=np.int64,
  177. )
  178. view = df["c"].iloc[:2].values
  179. # arr can be losslessly cast to int, so this setitem is inplace
  180. df.loc[4, "c"] = arr
  181. exp = Series(arr, index=[8, 10], name="c", dtype="int64")
  182. result = df.loc[4, "c"]
  183. tm.assert_series_equal(result, exp)
  184. # extra check for inplace-ness
  185. if not using_copy_on_write:
  186. tm.assert_numpy_array_equal(view, exp.values)
  187. # arr + 0.5 cannot be cast losslessly to int, so we upcast
  188. df.loc[4, "c"] = arr + 0.5
  189. result = df.loc[4, "c"]
  190. exp = exp + 0.5
  191. tm.assert_series_equal(result, exp)
  192. # scalar ok
  193. df.loc[4, "c"] = 10
  194. exp = Series(10, index=[8, 10], name="c", dtype="float64")
  195. tm.assert_series_equal(df.loc[4, "c"], exp)
  196. # invalid assignments
  197. msg = "Must have equal len keys and value when setting with an iterable"
  198. with pytest.raises(ValueError, match=msg):
  199. df.loc[4, "c"] = [0, 1, 2, 3]
  200. with pytest.raises(ValueError, match=msg):
  201. df.loc[4, "c"] = [0]
  202. # But with a length-1 listlike column indexer this behaves like
  203. # `df.loc[4, "c"] = 0
  204. df.loc[4, ["c"]] = [0]
  205. assert (df.loc[4, "c"] == 0).all()
  206. def test_groupby_example(self):
  207. # groupby example
  208. NUM_ROWS = 100
  209. NUM_COLS = 10
  210. col_names = ["A" + num for num in map(str, np.arange(NUM_COLS).tolist())]
  211. index_cols = col_names[:5]
  212. df = DataFrame(
  213. np.random.randint(5, size=(NUM_ROWS, NUM_COLS)),
  214. dtype=np.int64,
  215. columns=col_names,
  216. )
  217. df = df.set_index(index_cols).sort_index()
  218. grp = df.groupby(level=index_cols[:4])
  219. df["new_col"] = np.nan
  220. # we are actually operating on a copy here
  221. # but in this case, that's ok
  222. for name, df2 in grp:
  223. new_vals = np.arange(df2.shape[0])
  224. df.loc[name, "new_col"] = new_vals
  225. def test_series_setitem(self, multiindex_year_month_day_dataframe_random_data):
  226. ymd = multiindex_year_month_day_dataframe_random_data
  227. s = ymd["A"]
  228. s[2000, 3] = np.nan
  229. assert isna(s.values[42:65]).all()
  230. assert notna(s.values[:42]).all()
  231. assert notna(s.values[65:]).all()
  232. s[2000, 3, 10] = np.nan
  233. assert isna(s.iloc[49])
  234. with pytest.raises(KeyError, match="49"):
  235. # GH#33355 dont fall-back to positional when leading level is int
  236. s[49]
  237. def test_frame_getitem_setitem_boolean(self, multiindex_dataframe_random_data):
  238. frame = multiindex_dataframe_random_data
  239. df = frame.T.copy()
  240. values = df.values.copy()
  241. result = df[df > 0]
  242. expected = df.where(df > 0)
  243. tm.assert_frame_equal(result, expected)
  244. df[df > 0] = 5
  245. values[values > 0] = 5
  246. tm.assert_almost_equal(df.values, values)
  247. df[df == 5] = 0
  248. values[values == 5] = 0
  249. tm.assert_almost_equal(df.values, values)
  250. # a df that needs alignment first
  251. df[df[:-1] < 0] = 2
  252. np.putmask(values[:-1], values[:-1] < 0, 2)
  253. tm.assert_almost_equal(df.values, values)
  254. with pytest.raises(TypeError, match="boolean values only"):
  255. df[df * 0] = 2
  256. def test_frame_getitem_setitem_multislice(self):
  257. levels = [["t1", "t2"], ["a", "b", "c"]]
  258. codes = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]]
  259. midx = MultiIndex(codes=codes, levels=levels, names=[None, "id"])
  260. df = DataFrame({"value": [1, 2, 3, 7, 8]}, index=midx)
  261. result = df.loc[:, "value"]
  262. tm.assert_series_equal(df["value"], result)
  263. result = df.loc[df.index[1:3], "value"]
  264. tm.assert_series_equal(df["value"][1:3], result)
  265. result = df.loc[:, :]
  266. tm.assert_frame_equal(df, result)
  267. result = df
  268. df.loc[:, "value"] = 10
  269. result["value"] = 10
  270. tm.assert_frame_equal(df, result)
  271. df.loc[:, :] = 10
  272. tm.assert_frame_equal(df, result)
  273. def test_frame_setitem_multi_column(self):
  274. df = DataFrame(
  275. np.random.randn(10, 4), columns=[["a", "a", "b", "b"], [0, 1, 0, 1]]
  276. )
  277. cp = df.copy()
  278. cp["a"] = cp["b"]
  279. tm.assert_frame_equal(cp["a"], cp["b"])
  280. # set with ndarray
  281. cp = df.copy()
  282. cp["a"] = cp["b"].values
  283. tm.assert_frame_equal(cp["a"], cp["b"])
  284. def test_frame_setitem_multi_column2(self):
  285. # ---------------------------------------
  286. # GH#1803
  287. columns = MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")])
  288. df = DataFrame(index=[1, 3, 5], columns=columns)
  289. # Works, but adds a column instead of updating the two existing ones
  290. df["A"] = 0.0 # Doesn't work
  291. assert (df["A"].values == 0).all()
  292. # it broadcasts
  293. df["B", "1"] = [1, 2, 3]
  294. df["A"] = df["B", "1"]
  295. sliced_a1 = df["A", "1"]
  296. sliced_a2 = df["A", "2"]
  297. sliced_b1 = df["B", "1"]
  298. tm.assert_series_equal(sliced_a1, sliced_b1, check_names=False)
  299. tm.assert_series_equal(sliced_a2, sliced_b1, check_names=False)
  300. assert sliced_a1.name == ("A", "1")
  301. assert sliced_a2.name == ("A", "2")
  302. assert sliced_b1.name == ("B", "1")
  303. def test_loc_getitem_tuple_plus_columns(
  304. self, multiindex_year_month_day_dataframe_random_data
  305. ):
  306. # GH #1013
  307. ymd = multiindex_year_month_day_dataframe_random_data
  308. df = ymd[:5]
  309. result = df.loc[(2000, 1, 6), ["A", "B", "C"]]
  310. expected = df.loc[2000, 1, 6][["A", "B", "C"]]
  311. tm.assert_series_equal(result, expected)
  312. def test_loc_getitem_setitem_slice_integers(self, frame_or_series):
  313. index = MultiIndex(
  314. levels=[[0, 1, 2], [0, 2]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]
  315. )
  316. obj = DataFrame(
  317. np.random.randn(len(index), 4), index=index, columns=["a", "b", "c", "d"]
  318. )
  319. obj = tm.get_obj(obj, frame_or_series)
  320. res = obj.loc[1:2]
  321. exp = obj.reindex(obj.index[2:])
  322. tm.assert_equal(res, exp)
  323. obj.loc[1:2] = 7
  324. assert (obj.loc[1:2] == 7).values.all()
  325. def test_setitem_change_dtype(self, multiindex_dataframe_random_data):
  326. frame = multiindex_dataframe_random_data
  327. dft = frame.T
  328. s = dft["foo", "two"]
  329. dft["foo", "two"] = s > s.median()
  330. tm.assert_series_equal(dft["foo", "two"], s > s.median())
  331. # assert isinstance(dft._data.blocks[1].items, MultiIndex)
  332. reindexed = dft.reindex(columns=[("foo", "two")])
  333. tm.assert_series_equal(reindexed["foo", "two"], s > s.median())
  334. def test_set_column_scalar_with_loc(
  335. self, multiindex_dataframe_random_data, using_copy_on_write
  336. ):
  337. frame = multiindex_dataframe_random_data
  338. subset = frame.index[[1, 4, 5]]
  339. frame.loc[subset] = 99
  340. assert (frame.loc[subset].values == 99).all()
  341. frame_original = frame.copy()
  342. col = frame["B"]
  343. col[subset] = 97
  344. if using_copy_on_write:
  345. # chained setitem doesn't work with CoW
  346. tm.assert_frame_equal(frame, frame_original)
  347. else:
  348. assert (frame.loc[subset, "B"] == 97).all()
  349. def test_nonunique_assignment_1750(self):
  350. df = DataFrame(
  351. [[1, 1, "x", "X"], [1, 1, "y", "Y"], [1, 2, "z", "Z"]], columns=list("ABCD")
  352. )
  353. df = df.set_index(["A", "B"])
  354. mi = MultiIndex.from_tuples([(1, 1)])
  355. df.loc[mi, "C"] = "_"
  356. assert (df.xs((1, 1))["C"] == "_").all()
  357. def test_astype_assignment_with_dups(self):
  358. # GH 4686
  359. # assignment with dups that has a dtype change
  360. cols = MultiIndex.from_tuples([("A", "1"), ("B", "1"), ("A", "2")])
  361. df = DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object)
  362. index = df.index.copy()
  363. df["A"] = df["A"].astype(np.float64)
  364. tm.assert_index_equal(df.index, index)
  365. def test_setitem_nonmonotonic(self):
  366. # https://github.com/pandas-dev/pandas/issues/31449
  367. index = MultiIndex.from_tuples(
  368. [("a", "c"), ("b", "x"), ("a", "d")], names=["l1", "l2"]
  369. )
  370. df = DataFrame(data=[0, 1, 2], index=index, columns=["e"])
  371. df.loc["a", "e"] = np.arange(99, 101, dtype="int64")
  372. expected = DataFrame({"e": [99, 1, 100]}, index=index)
  373. tm.assert_frame_equal(df, expected)
  374. class TestSetitemWithExpansionMultiIndex:
  375. def test_setitem_new_column_mixed_depth(self):
  376. arrays = [
  377. ["a", "top", "top", "routine1", "routine1", "routine2"],
  378. ["", "OD", "OD", "result1", "result2", "result1"],
  379. ["", "wx", "wy", "", "", ""],
  380. ]
  381. tuples = sorted(zip(*arrays))
  382. index = MultiIndex.from_tuples(tuples)
  383. df = DataFrame(np.random.randn(4, 6), columns=index)
  384. result = df.copy()
  385. expected = df.copy()
  386. result["b"] = [1, 2, 3, 4]
  387. expected["b", "", ""] = [1, 2, 3, 4]
  388. tm.assert_frame_equal(result, expected)
  389. def test_setitem_new_column_all_na(self):
  390. # GH#1534
  391. mix = MultiIndex.from_tuples([("1a", "2a"), ("1a", "2b"), ("1a", "2c")])
  392. df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix)
  393. s = Series({(1, 1): 1, (1, 2): 2})
  394. df["new"] = s
  395. assert df["new"].isna().all()
  396. def test_setitem_enlargement_keep_index_names(self):
  397. # GH#53053
  398. mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
  399. df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
  400. df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
  401. mi_expected = MultiIndex.from_tuples(
  402. [(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
  403. )
  404. expected = DataFrame(
  405. data=[[10, 20, 30], [10, 20, 30]],
  406. index=mi_expected,
  407. columns=["A", "B", "C"],
  408. )
  409. tm.assert_frame_equal(df, expected)
  410. @td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
  411. # is not a view
  412. def test_frame_setitem_view_direct(
  413. multiindex_dataframe_random_data, using_copy_on_write
  414. ):
  415. # this works because we are modifying the underlying array
  416. # really a no-no
  417. df = multiindex_dataframe_random_data.T
  418. if using_copy_on_write:
  419. with pytest.raises(ValueError, match="read-only"):
  420. df["foo"].values[:] = 0
  421. assert (df["foo"].values != 0).all()
  422. else:
  423. df["foo"].values[:] = 0
  424. assert (df["foo"].values == 0).all()
  425. def test_frame_setitem_copy_raises(
  426. multiindex_dataframe_random_data, using_copy_on_write
  427. ):
  428. # will raise/warn as its chained assignment
  429. df = multiindex_dataframe_random_data.T
  430. if using_copy_on_write:
  431. with tm.raises_chained_assignment_error():
  432. df["foo"]["one"] = 2
  433. else:
  434. msg = "A value is trying to be set on a copy of a slice from a DataFrame"
  435. with pytest.raises(SettingWithCopyError, match=msg):
  436. df["foo"]["one"] = 2
  437. def test_frame_setitem_copy_no_write(
  438. multiindex_dataframe_random_data, using_copy_on_write
  439. ):
  440. frame = multiindex_dataframe_random_data.T
  441. expected = frame
  442. df = frame.copy()
  443. if using_copy_on_write:
  444. with tm.raises_chained_assignment_error():
  445. df["foo"]["one"] = 2
  446. else:
  447. msg = "A value is trying to be set on a copy of a slice from a DataFrame"
  448. with pytest.raises(SettingWithCopyError, match=msg):
  449. df["foo"]["one"] = 2
  450. result = df
  451. tm.assert_frame_equal(result, expected)