Best Python code snippet using autotest_python
test_rename.py
Source:test_rename.py
...3import pytest4from pandas import DataFrame, Index, MultiIndex5import pandas._testing as tm6class TestRename:7 def test_rename(self, float_frame):8 mapping = {"A": "a", "B": "b", "C": "c", "D": "d"}9 renamed = float_frame.rename(columns=mapping)10 renamed2 = float_frame.rename(columns=str.lower)11 tm.assert_frame_equal(renamed, renamed2)12 tm.assert_frame_equal(13 renamed2.rename(columns=str.upper), float_frame, check_names=False14 )15 # index16 data = {"A": {"foo": 0, "bar": 1}}17 # gets sorted alphabetical18 df = DataFrame(data)19 renamed = df.rename(index={"foo": "bar", "bar": "foo"})20 tm.assert_index_equal(renamed.index, Index(["foo", "bar"]))21 renamed = df.rename(index=str.upper)22 tm.assert_index_equal(renamed.index, Index(["BAR", "FOO"]))23 # have to pass something24 with pytest.raises(TypeError, match="must pass an index to rename"):25 float_frame.rename()26 # partial columns27 renamed = float_frame.rename(columns={"C": "foo", "D": "bar"})28 tm.assert_index_equal(renamed.columns, Index(["A", "B", "foo", "bar"]))29 # other axis30 renamed = float_frame.T.rename(index={"C": "foo", "D": "bar"})31 tm.assert_index_equal(renamed.index, Index(["A", "B", "foo", "bar"]))32 # index with name33 index = Index(["foo", "bar"], name="name")34 renamer = DataFrame(data, index=index)35 renamed = renamer.rename(index={"foo": "bar", "bar": "foo"})36 tm.assert_index_equal(renamed.index, Index(["bar", "foo"], name="name"))37 assert renamed.index.name == renamer.index.name38 @pytest.mark.parametrize(39 "args,kwargs",40 [41 ((ChainMap({"A": "a"}, {"B": "b"}),), dict(axis="columns")),42 ((), dict(columns=ChainMap({"A": "a"}, {"B": "b"}))),43 ],44 )45 def test_rename_chainmap(self, args, kwargs):46 # see gh-2385947 colAData = range(1, 11)48 colBdata = np.random.randn(10)49 df = DataFrame({"A": colAData, "B": colBdata})50 result = df.rename(*args, **kwargs)51 expected = DataFrame({"a": colAData, "b": colBdata})52 tm.assert_frame_equal(result, expected)53 def test_rename_multiindex(self):54 tuples_index = [("foo1", "bar1"), ("foo2", "bar2")]55 tuples_columns = [("fizz1", "buzz1"), ("fizz2", "buzz2")]56 index = MultiIndex.from_tuples(tuples_index, names=["foo", "bar"])57 columns = MultiIndex.from_tuples(tuples_columns, names=["fizz", "buzz"])58 df = DataFrame([(0, 0), (1, 1)], index=index, columns=columns)59 #60 # without specifying level -> across all levels61 renamed = df.rename(62 index={"foo1": "foo3", "bar2": "bar3"},63 columns={"fizz1": "fizz3", "buzz2": "buzz3"},64 )65 new_index = MultiIndex.from_tuples(66 [("foo3", "bar1"), ("foo2", "bar3")], names=["foo", "bar"]67 )68 new_columns = MultiIndex.from_tuples(69 [("fizz3", "buzz1"), ("fizz2", "buzz3")], names=["fizz", "buzz"]70 )71 tm.assert_index_equal(renamed.index, new_index)72 tm.assert_index_equal(renamed.columns, new_columns)73 assert renamed.index.names == df.index.names74 assert renamed.columns.names == df.columns.names75 #76 # with specifying a level (GH13766)77 # dict78 new_columns = MultiIndex.from_tuples(79 [("fizz3", "buzz1"), ("fizz2", "buzz2")], names=["fizz", "buzz"]80 )81 renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level=0)82 tm.assert_index_equal(renamed.columns, new_columns)83 renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level="fizz")84 tm.assert_index_equal(renamed.columns, new_columns)85 new_columns = MultiIndex.from_tuples(86 [("fizz1", "buzz1"), ("fizz2", "buzz3")], names=["fizz", "buzz"]87 )88 renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level=1)89 tm.assert_index_equal(renamed.columns, new_columns)90 renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level="buzz")91 tm.assert_index_equal(renamed.columns, new_columns)92 # function93 func = str.upper94 new_columns = MultiIndex.from_tuples(95 [("FIZZ1", "buzz1"), ("FIZZ2", "buzz2")], names=["fizz", "buzz"]96 )97 renamed = df.rename(columns=func, level=0)98 tm.assert_index_equal(renamed.columns, new_columns)99 renamed = df.rename(columns=func, level="fizz")100 tm.assert_index_equal(renamed.columns, new_columns)101 new_columns = MultiIndex.from_tuples(102 [("fizz1", "BUZZ1"), ("fizz2", "BUZZ2")], names=["fizz", "buzz"]103 )104 renamed = df.rename(columns=func, level=1)105 tm.assert_index_equal(renamed.columns, new_columns)106 renamed = df.rename(columns=func, level="buzz")107 tm.assert_index_equal(renamed.columns, new_columns)108 # index109 new_index = MultiIndex.from_tuples(110 [("foo3", "bar1"), ("foo2", "bar2")], names=["foo", "bar"]111 )112 renamed = df.rename(index={"foo1": "foo3", "bar2": "bar3"}, level=0)113 tm.assert_index_equal(renamed.index, new_index)114 def test_rename_nocopy(self, float_frame):115 renamed = float_frame.rename(columns={"C": "foo"}, copy=False)116 renamed["foo"] = 1.0117 assert (float_frame["C"] == 1.0).all()118 def test_rename_inplace(self, float_frame):119 float_frame.rename(columns={"C": "foo"})120 assert "C" in float_frame121 assert "foo" not in float_frame122 c_id = id(float_frame["C"])123 float_frame = float_frame.copy()124 return_value = float_frame.rename(columns={"C": "foo"}, inplace=True)125 assert return_value is None126 assert "C" not in float_frame127 assert "foo" in float_frame128 assert id(float_frame["foo"]) != c_id129 def test_rename_bug(self):130 # GH 5344131 # rename set ref_locs, and set_index was not resetting132 df = DataFrame({0: ["foo", "bar"], 1: ["bah", "bas"], 2: [1, 2]})133 df = df.rename(columns={0: "a"})134 df = df.rename(columns={1: "b"})135 df = df.set_index(["a", "b"])136 df.columns = ["2001-01-01"]137 expected = DataFrame(138 [[1], [2]],139 index=MultiIndex.from_tuples(140 [("foo", "bah"), ("bar", "bas")], names=["a", "b"]141 ),142 columns=["2001-01-01"],143 )144 tm.assert_frame_equal(df, expected)145 def test_rename_bug2(self):146 # GH 19497147 # rename was changing Index to MultiIndex if Index contained tuples148 df = DataFrame(data=np.arange(3), index=[(0, 0), (1, 1), (2, 2)], columns=["a"])149 df = df.rename({(1, 1): (5, 4)}, axis="index")150 expected = DataFrame(151 data=np.arange(3), index=[(0, 0), (5, 4), (2, 2)], columns=["a"]152 )153 tm.assert_frame_equal(df, expected)154 def test_rename_errors_raises(self):155 df = DataFrame(columns=["A", "B", "C", "D"])156 with pytest.raises(KeyError, match="'E'] not found in axis"):157 df.rename(columns={"A": "a", "E": "e"}, errors="raise")158 @pytest.mark.parametrize(159 "mapper, errors, expected_columns",160 [161 ({"A": "a", "E": "e"}, "ignore", ["a", "B", "C", "D"]),162 ({"A": "a"}, "raise", ["a", "B", "C", "D"]),163 (str.lower, "raise", ["a", "b", "c", "d"]),164 ],165 )166 def test_rename_errors(self, mapper, errors, expected_columns):167 # GH 13473168 # rename now works with errors parameter169 df = DataFrame(columns=["A", "B", "C", "D"])170 result = df.rename(columns=mapper, errors=errors)171 expected = DataFrame(columns=expected_columns)172 tm.assert_frame_equal(result, expected)173 def test_rename_objects(self, float_string_frame):174 renamed = float_string_frame.rename(columns=str.upper)175 assert "FOO" in renamed176 assert "foo" not in renamed177 def test_rename_axis_style(self):178 # https://github.com/pandas-dev/pandas/issues/12392179 df = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["X", "Y"])180 expected = DataFrame({"a": [1, 2], "b": [1, 2]}, index=["X", "Y"])181 result = df.rename(str.lower, axis=1)182 tm.assert_frame_equal(result, expected)183 result = df.rename(str.lower, axis="columns")184 tm.assert_frame_equal(result, expected)185 result = df.rename({"A": "a", "B": "b"}, axis=1)186 tm.assert_frame_equal(result, expected)187 result = df.rename({"A": "a", "B": "b"}, axis="columns")188 tm.assert_frame_equal(result, expected)189 # Index190 expected = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["x", "y"])191 result = df.rename(str.lower, axis=0)192 tm.assert_frame_equal(result, expected)193 result = df.rename(str.lower, axis="index")194 tm.assert_frame_equal(result, expected)195 result = df.rename({"X": "x", "Y": "y"}, axis=0)196 tm.assert_frame_equal(result, expected)197 result = df.rename({"X": "x", "Y": "y"}, axis="index")198 tm.assert_frame_equal(result, expected)199 result = df.rename(mapper=str.lower, axis="index")200 tm.assert_frame_equal(result, expected)201 def test_rename_mapper_multi(self):202 df = DataFrame({"A": ["a", "b"], "B": ["c", "d"], "C": [1, 2]}).set_index(203 ["A", "B"]204 )205 result = df.rename(str.upper)206 expected = df.rename(index=str.upper)207 tm.assert_frame_equal(result, expected)208 def test_rename_positional_named(self):209 # https://github.com/pandas-dev/pandas/issues/12392210 df = DataFrame({"a": [1, 2], "b": [1, 2]}, index=["X", "Y"])211 result = df.rename(index=str.lower, columns=str.upper)212 expected = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["x", "y"])213 tm.assert_frame_equal(result, expected)214 def test_rename_axis_style_raises(self):215 # see gh-12392216 df = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["0", "1"])217 # Named target and axis218 over_spec_msg = "Cannot specify both 'axis' and any of 'index' or 'columns'"219 with pytest.raises(TypeError, match=over_spec_msg):220 df.rename(index=str.lower, axis=1)221 with pytest.raises(TypeError, match=over_spec_msg):222 df.rename(index=str.lower, axis="columns")223 with pytest.raises(TypeError, match=over_spec_msg):224 df.rename(columns=str.lower, axis="columns")225 with pytest.raises(TypeError, match=over_spec_msg):226 df.rename(index=str.lower, axis=0)227 # Multiple targets and axis228 with pytest.raises(TypeError, match=over_spec_msg):229 df.rename(str.lower, index=str.lower, axis="columns")230 # Too many targets231 over_spec_msg = "Cannot specify both 'mapper' and any of 'index' or 'columns'"232 with pytest.raises(TypeError, match=over_spec_msg):233 df.rename(str.lower, index=str.lower, columns=str.lower)234 # Duplicates235 with pytest.raises(TypeError, match="multiple values"):236 df.rename(id, mapper=id)237 def test_rename_positional_raises(self):238 # GH 29136239 df = DataFrame(columns=["A", "B"])240 msg = r"rename\(\) takes from 1 to 2 positional arguments"241 with pytest.raises(TypeError, match=msg):242 df.rename(None, str.lower)243 def test_rename_no_mappings_raises(self):244 # GH 29136245 df = DataFrame([[1]])246 msg = "must pass an index to rename"247 with pytest.raises(TypeError, match=msg):248 df.rename()249 with pytest.raises(TypeError, match=msg):250 df.rename(None, index=None)251 with pytest.raises(TypeError, match=msg):252 df.rename(None, columns=None)253 with pytest.raises(TypeError, match=msg):254 df.rename(None, columns=None, index=None)255 def test_rename_mapper_and_positional_arguments_raises(self):256 # GH 29136257 df = DataFrame([[1]])258 msg = "Cannot specify both 'mapper' and any of 'index' or 'columns'"259 with pytest.raises(TypeError, match=msg):260 df.rename({}, index={})261 with pytest.raises(TypeError, match=msg):262 df.rename({}, columns={})263 with pytest.raises(TypeError, match=msg):...
json_compact.py
Source:json_compact.py
...62 del item["attrs"]["var"]63 assert item["type_key"].startswith("relay.")64 item["type_key"] = item["type_key"][len("relay.") :]65 return item66 def _rename(new_name):67 def _convert(item, _):68 item["type_key"] = new_name69 return item70 return _convert71 def _update_tir_var(new_name):72 def _convert(item, _):73 item["type_key"] = new_name74 item["attrs"]["type_annotation"] = "0"75 return item76 return _convert77 def _update_global_key(item, _):78 if "global_key" in item:79 item["repr_str"] = item["global_key"]80 del item["global_key"]81 return item82 def _update_from_std_str(key):83 def _convert(item, nodes):84 str_val = item["attrs"][key]85 jdata = json.loads(tvm.ir.save_json(tvm.runtime.String(str_val)))86 root_idx = jdata["root"]87 val = jdata["nodes"][root_idx]88 sidx = len(nodes)89 nodes.append(val)90 item["attrs"][key] = "%d" % sidx91 return item92 return _convert93 node_map = {94 # Base IR95 "SourceName": _update_global_key,96 "EnvFunc": _update_global_key,97 "relay.Op": [_update_global_key, _rename("Op")],98 "relay.TypeVar": [_ftype_var, _update_from_std_str("name_hint")],99 "TypeVar": _update_from_std_str("name_hint"),100 "relay.Id": [_update_from_std_str("name_hint")],101 "relay.GlobalTypeVar": [_ftype_var, _update_from_std_str("name_hint")],102 "GlobalTypeVar": _update_from_std_str("name_hint"),103 "relay.Type": _rename("Type"),104 "relay.TupleType": _rename("TupleType"),105 "relay.TypeConstraint": _rename("TypeConstraint"),106 "relay.FuncType": _rename("FuncType"),107 "relay.IncompleteType": _rename("IncompleteType"),108 "relay.TypeRelation": _rename("TypeRelation"),109 "relay.TypeCall": _rename("TypeCall"),110 "relay.Constructor": [_update_from_std_str("name_hint")],111 "relay.Module": _rename("IRModule"),112 "relay.SourceName": _rename("SourceName"),113 "relay.Span": _rename("Span"),114 "relay.GlobalVar": [_rename("GlobalVar"), _update_from_std_str("name_hint")],115 "GlobalVar": _update_from_std_str("name_hint"),116 "relay.Pass": _rename("transform.Pass"),117 "relay.PassInfo": _rename("transform.PassInfo"),118 "relay.PassContext": _rename("transform.PassContext"),119 "relay.ModulePass": _rename("transform.ModulePass"),120 "relay.Sequential": _rename("transform.Sequential"),121 "StrMap": _rename("Map"),122 # TIR123 "Variable": [_update_tir_var("tir.Var"), _update_from_std_str("name")],124 "SizeVar": [_update_tir_var("tir.SizeVar"), _update_from_std_str("name")],125 "StringImm": [_rename("tir.StringImm"), _update_from_std_str("value")],126 "Cast": [_rename("tir.Cast")],127 "Add": [_rename("tir.Add")],128 "Sub": [_rename("tir.Sub")],129 "Mul": [_rename("tir.Mul")],130 "Div": [_rename("tir.Div")],131 "Mod": [_rename("tir.Mod")],132 "FloorDiv": [_rename("tir.FloorDiv")],133 "FloorMod": [_rename("tir.FloorMod")],134 "Min": [_rename("tir.Min")],135 "Max": [_rename("tir.Max")],136 "EQ": [_rename("tir.EQ")],137 "NE": [_rename("tir.NE")],138 "LT": [_rename("tir.LT")],139 "LE": [_rename("tir.LE")],140 "GT": [_rename("tir.GT")],141 "GE": [_rename("tir.GE")],142 "And": [_rename("tir.And")],143 "Or": [_rename("tir.Or")],144 "Not": [_rename("tir.Not")],145 "Select": [_rename("tir.Select")],146 "Load": [_rename("tir.Load")],147 "BufferLoad": [_rename("tir.BufferLoad")],148 "Ramp": [_rename("tir.Ramp")],149 "Broadcast": [_rename("tir.Broadcast")],150 "Shuffle": [_rename("tir.Shuffle")],151 "Call": [_rename("tir.Call"), _update_from_std_str("name")],152 "Let": [_rename("tir.Let")],153 "Any": [_rename("tir.Any")],154 "LetStmt": [_rename("tir.LetStmt")],155 "AssertStmt": [_rename("tir.AssertStmt")],156 "Store": [_rename("tir.Store")],157 "BufferStore": [_rename("tir.BufferStore")],158 "BufferRealize": [_rename("tir.BufferRealize")],159 "Allocate": [_rename("tir.Allocate")],160 "IfThenElse": [_rename("tir.IfThenElse")],161 "Evaluate": [_rename("tir.Evaluate")],162 "Prefetch": [_rename("tir.Prefetch")],163 "AttrStmt": [_rename("tir.AttrStmt"), _update_from_std_str("attr_key")],164 "Layout": [_rename("tir.Layout"), _update_from_std_str("name")],165 "Buffer": [166 _rename("tir.Buffer"),167 _update_from_std_str("name"),168 _update_from_std_str("scope"),169 ],170 }171 return create_updater(node_map, "0.6", "0.7")172def upgrade_json(json_str):173 """Update json from a historical version.174 Parameters175 ----------176 json_str : str177 A historical json file.178 Returns179 -------180 updated_json : str...
test_rename_axis.py
Source:test_rename_axis.py
...78 columns = Index(["col1", "col2"], name="bar")79 data = np.arange(6).reshape(3, 2)80 df = DataFrame(data, index, columns)81 result = df.rename_axis(**kwargs)82 expected_index = index.rename(None) if rename_index else index83 expected_columns = columns.rename(None) if rename_columns else columns84 expected = DataFrame(data, expected_index, expected_columns)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!