|
5 | 5 | import pytest |
6 | 6 |
|
7 | 7 | from pandas import ( |
| 8 | + NA, |
8 | 9 | DataFrame, |
9 | 10 | Index, |
10 | 11 | MultiIndex, |
11 | 12 | Series, |
| 13 | + array, |
12 | 14 | merge, |
13 | 15 | ) |
14 | 16 | import pandas._testing as tm |
@@ -411,6 +413,64 @@ def test_rename_boolean_index(self): |
411 | 413 | ) |
412 | 414 | tm.assert_frame_equal(res, exp) |
413 | 415 |
|
| 416 | + def test_rename_preserves_nullable_int_index(self): |
| 417 | + # GH#65315 |
| 418 | + df = DataFrame( |
| 419 | + {"val": [1, 2, 3]}, |
| 420 | + index=Index(array([1, 2, 3], dtype="Int64"), name="id"), |
| 421 | + ) |
| 422 | + result = df.rename({1: 9}) |
| 423 | + expected = Index(array([9, 2, 3], dtype="Int64"), name="id") |
| 424 | + tm.assert_index_equal(result.index, expected) |
| 425 | + |
| 426 | + def test_rename_preserves_nullable_float_columns(self): |
| 427 | + # GH#65315 |
| 428 | + df = DataFrame( |
| 429 | + [[1, 2, 3]], |
| 430 | + columns=Index(array([1.0, 2.0, 3.0], dtype="Float64")), |
| 431 | + ) |
| 432 | + result = df.rename(columns={1.0: 9.0}) |
| 433 | + expected = Index(array([9.0, 2.0, 3.0], dtype="Float64")) |
| 434 | + tm.assert_index_equal(result.columns, expected) |
| 435 | + |
| 436 | + def test_rename_nullable_index_to_na(self): |
| 437 | + # GH#65315 |
| 438 | + df = DataFrame( |
| 439 | + {"val": [1, 2, 3]}, |
| 440 | + index=Index(array([1, 2, 3], dtype="Int64")), |
| 441 | + ) |
| 442 | + result = df.rename({1: NA}) |
| 443 | + expected = Index(array([NA, 2, 3], dtype="Int64")) |
| 444 | + tm.assert_index_equal(result.index, expected) |
| 445 | + |
| 446 | + def test_rename_empty_nullable_index(self): |
| 447 | + # GH#65315 |
| 448 | + df = DataFrame({"val": []}, index=Index(array([], dtype="Int64"))) |
| 449 | + result = df.rename(index={}) |
| 450 | + tm.assert_index_equal(result.index, df.index) |
| 451 | + |
| 452 | + def test_rename_nullable_index_type_change_widens(self): |
| 453 | + # GH#65315 |
| 454 | + df = DataFrame( |
| 455 | + {"val": [1, 2, 3]}, |
| 456 | + index=Index(array([1, 2, 3], dtype="Int64")), |
| 457 | + ) |
| 458 | + result = df.rename(lambda x: f"label_{x}") |
| 459 | + assert list(result.index) == ["label_1", "label_2", "label_3"] |
| 460 | + assert result.index.dtype != "Int64" |
| 461 | + |
| 462 | + def test_rename_tuple_columns_not_multiindex(self): |
| 463 | + # GH#65315 |
| 464 | + df = DataFrame( |
| 465 | + [[1, 2]], |
| 466 | + columns=Index(array([1, 2], dtype="Int64")), |
| 467 | + ) |
| 468 | + result = df.rename(columns=lambda x: (x, x)) |
| 469 | + assert not isinstance(result.columns, MultiIndex) |
| 470 | + tm.assert_index_equal( |
| 471 | + result.columns, Index([(1, 1), (2, 2)], tupleize_cols=False) |
| 472 | + ) |
| 473 | + |
414 | 474 | def test_rename_non_unique_index_series(self): |
415 | 475 | # GH#58621 |
416 | 476 | df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) |
|
0 commit comments