|
1 | 1 | import numpy as np
|
2 | 2 | import pytest
|
3 | 3 |
|
4 |
| -from pandas import DataFrame, Index, Series |
| 4 | +from pandas import Categorical, DataFrame, Index, Series, Timestamp, date_range |
5 | 5 | import pandas._testing as tm
|
| 6 | +from pandas.core.arrays import SparseArray |
6 | 7 |
|
7 |
| -# Column add, remove, delete. |
8 | 8 |
|
9 |
| - |
10 |
| -class TestDataFrameMutateColumns: |
| 9 | +class TestDataFrameSetItem: |
11 | 10 | def test_setitem_error_msmgs(self):
|
12 | 11 |
|
13 | 12 | # GH 7432
|
@@ -84,3 +83,46 @@ def test_setitem_empty_columns(self):
|
84 | 83 | df["X"] = ["x", "y", "z"]
|
85 | 84 | exp = DataFrame(data={"X": ["x", "y", "z"]}, index=["A", "B", "C"])
|
86 | 85 | tm.assert_frame_equal(df, exp)
|
| 86 | + |
| 87 | + def test_setitem_dt64_index_empty_columns(self): |
| 88 | + rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") |
| 89 | + df = DataFrame(index=np.arange(len(rng))) |
| 90 | + |
| 91 | + df["A"] = rng |
| 92 | + assert df["A"].dtype == np.dtype("M8[ns]") |
| 93 | + |
| 94 | + def test_setitem_timestamp_empty_columns(self): |
| 95 | + # GH#19843 |
| 96 | + df = DataFrame(index=range(3)) |
| 97 | + df["now"] = Timestamp("20130101", tz="UTC") |
| 98 | + |
| 99 | + expected = DataFrame( |
| 100 | + [[Timestamp("20130101", tz="UTC")]] * 3, index=[0, 1, 2], columns=["now"], |
| 101 | + ) |
| 102 | + tm.assert_frame_equal(df, expected) |
| 103 | + |
| 104 | + def test_setitem_wrong_length_categorical_dtype_raises(self): |
| 105 | + # GH#29523 |
| 106 | + cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) |
| 107 | + df = DataFrame(range(10), columns=["bar"]) |
| 108 | + |
| 109 | + msg = "Length of values does not match length of index" |
| 110 | + with pytest.raises(ValueError, match=msg): |
| 111 | + df["foo"] = cat |
| 112 | + |
| 113 | + def test_setitem_with_sparse_value(self): |
| 114 | + # GH#8131 |
| 115 | + df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) |
| 116 | + sp_array = SparseArray([0, 0, 1]) |
| 117 | + df["new_column"] = sp_array |
| 118 | + |
| 119 | + expected = Series(sp_array, name="new_column") |
| 120 | + tm.assert_series_equal(df["new_column"], expected) |
| 121 | + |
| 122 | + def test_setitem_with_unaligned_sparse_value(self): |
| 123 | + df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) |
| 124 | + sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0]) |
| 125 | + |
| 126 | + df["new_column"] = sp_series |
| 127 | + expected = Series(SparseArray([1, 0, 0]), name="new_column") |
| 128 | + tm.assert_series_equal(df["new_column"], expected) |
0 commit comments