Skip to content

Commit 92f837f

Browse files
authored
TST: move DataFrame.applymap tests to tests/frame/methods/test_map.py (#52402)
1 parent 8d3357f commit 92f837f

File tree

3 files changed

+207
-187
lines changed

3 files changed

+207
-187
lines changed

pandas/tests/apply/test_frame_apply.py

-181
Original file line numberDiff line numberDiff line change
@@ -528,161 +528,6 @@ def test_apply_dict(df, dicts):
528528
tm.assert_series_equal(reduce_none, dicts)
529529

530530

531-
def test_applymap(float_frame):
532-
applied = float_frame.applymap(lambda x: x * 2)
533-
tm.assert_frame_equal(applied, float_frame * 2)
534-
float_frame.applymap(type)
535-
536-
# GH 465: function returning tuples
537-
result = float_frame.applymap(lambda x: (x, x))["A"][0]
538-
assert isinstance(result, tuple)
539-
540-
541-
@pytest.mark.parametrize("val", [1, 1.0])
542-
def test_applymap_float_object_conversion(val):
543-
# GH 2909: object conversion to float in constructor?
544-
df = DataFrame(data=[val, "a"])
545-
result = df.applymap(lambda x: x).dtypes[0]
546-
assert result == object
547-
548-
549-
@pytest.mark.parametrize("na_action", [None, "ignore"])
550-
def test_applymap_keeps_dtype(na_action):
551-
# GH52219
552-
arr = Series(["a", np.nan, "b"])
553-
sparse_arr = arr.astype(pd.SparseDtype(object))
554-
df = DataFrame(data={"a": arr, "b": sparse_arr})
555-
556-
def func(x):
557-
return str.upper(x) if not pd.isna(x) else x
558-
559-
result = df.applymap(func, na_action=na_action)
560-
561-
expected_sparse = pd.array(["A", np.nan, "B"], dtype=pd.SparseDtype(object))
562-
expected_arr = expected_sparse.astype(object)
563-
expected = DataFrame({"a": expected_arr, "b": expected_sparse})
564-
565-
tm.assert_frame_equal(result, expected)
566-
567-
result_empty = df.iloc[:0, :].applymap(func, na_action=na_action)
568-
expected_empty = expected.iloc[:0, :]
569-
tm.assert_frame_equal(result_empty, expected_empty)
570-
571-
572-
def test_applymap_str():
573-
# GH 2786
574-
df = DataFrame(np.random.random((3, 4)))
575-
df2 = df.copy()
576-
cols = ["a", "a", "a", "a"]
577-
df.columns = cols
578-
579-
expected = df2.applymap(str)
580-
expected.columns = cols
581-
result = df.applymap(str)
582-
tm.assert_frame_equal(result, expected)
583-
584-
585-
@pytest.mark.parametrize(
586-
"col, val",
587-
[["datetime", Timestamp("20130101")], ["timedelta", pd.Timedelta("1 min")]],
588-
)
589-
def test_applymap_datetimelike(col, val):
590-
# datetime/timedelta
591-
df = DataFrame(np.random.random((3, 4)))
592-
df[col] = val
593-
result = df.applymap(str)
594-
assert result.loc[0, col] == str(df.loc[0, col])
595-
596-
597-
@pytest.mark.parametrize(
598-
"expected",
599-
[
600-
DataFrame(),
601-
DataFrame(columns=list("ABC")),
602-
DataFrame(index=list("ABC")),
603-
DataFrame({"A": [], "B": [], "C": []}),
604-
],
605-
)
606-
@pytest.mark.parametrize("func", [round, lambda x: x])
607-
def test_applymap_empty(expected, func):
608-
# GH 8222
609-
result = expected.applymap(func)
610-
tm.assert_frame_equal(result, expected)
611-
612-
613-
def test_applymap_kwargs():
614-
# GH 40652
615-
result = DataFrame([[1, 2], [3, 4]]).applymap(lambda x, y: x + y, y=2)
616-
expected = DataFrame([[3, 4], [5, 6]])
617-
tm.assert_frame_equal(result, expected)
618-
619-
620-
def test_applymap_na_ignore(float_frame):
621-
# GH 23803
622-
strlen_frame = float_frame.applymap(lambda x: len(str(x)))
623-
float_frame_with_na = float_frame.copy()
624-
mask = np.random.randint(0, 2, size=float_frame.shape, dtype=bool)
625-
float_frame_with_na[mask] = pd.NA
626-
strlen_frame_na_ignore = float_frame_with_na.applymap(
627-
lambda x: len(str(x)), na_action="ignore"
628-
)
629-
strlen_frame_with_na = strlen_frame.copy()
630-
strlen_frame_with_na[mask] = pd.NA
631-
tm.assert_frame_equal(strlen_frame_na_ignore, strlen_frame_with_na)
632-
633-
634-
def test_applymap_box_timestamps():
635-
# GH 2689, GH 2627
636-
ser = Series(date_range("1/1/2000", periods=10))
637-
638-
def func(x):
639-
return (x.hour, x.day, x.month)
640-
641-
# it works!
642-
DataFrame(ser).applymap(func)
643-
644-
645-
def test_applymap_box():
646-
# ufunc will not be boxed. Same test cases as the test_map_box
647-
df = DataFrame(
648-
{
649-
"a": [Timestamp("2011-01-01"), Timestamp("2011-01-02")],
650-
"b": [
651-
Timestamp("2011-01-01", tz="US/Eastern"),
652-
Timestamp("2011-01-02", tz="US/Eastern"),
653-
],
654-
"c": [pd.Timedelta("1 days"), pd.Timedelta("2 days")],
655-
"d": [
656-
pd.Period("2011-01-01", freq="M"),
657-
pd.Period("2011-01-02", freq="M"),
658-
],
659-
}
660-
)
661-
662-
result = df.applymap(lambda x: type(x).__name__)
663-
expected = DataFrame(
664-
{
665-
"a": ["Timestamp", "Timestamp"],
666-
"b": ["Timestamp", "Timestamp"],
667-
"c": ["Timedelta", "Timedelta"],
668-
"d": ["Period", "Period"],
669-
}
670-
)
671-
tm.assert_frame_equal(result, expected)
672-
673-
674-
def test_frame_apply_dont_convert_datetime64():
675-
from pandas.tseries.offsets import BDay
676-
677-
df = DataFrame({"x1": [datetime(1996, 1, 1)]})
678-
679-
df = df.applymap(lambda x: x + BDay())
680-
df = df.applymap(lambda x: x + BDay())
681-
682-
result = df.x1.dtype
683-
assert result == "M8[ns]"
684-
685-
686531
def test_apply_non_numpy_dtype():
687532
# GH 12244
688533
df = DataFrame({"dt": date_range("2015-01-01", periods=3, tz="Europe/Brussels")})
@@ -776,24 +621,6 @@ def non_reducing_function(row):
776621
assert values == list(df.a.to_list())
777622

778623

779-
def test_applymap_function_runs_once():
780-
df = DataFrame({"a": [1, 2, 3]})
781-
values = [] # Save values function is applied to
782-
783-
def reducing_function(val):
784-
values.append(val)
785-
786-
def non_reducing_function(val):
787-
values.append(val)
788-
return val
789-
790-
for func in [reducing_function, non_reducing_function]:
791-
del values[:]
792-
793-
df.applymap(func)
794-
assert values == df.a.to_list()
795-
796-
797624
def test_apply_with_byte_string():
798625
# GH 34529
799626
df = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"])
@@ -1587,14 +1414,6 @@ def test_apply_type():
15871414
index=["a", "b", "c"],
15881415
)
15891416

1590-
# applymap
1591-
result = df.applymap(type)
1592-
expected = DataFrame(
1593-
{"col1": [int, str, type], "col2": [float, datetime, float]},
1594-
index=["a", "b", "c"],
1595-
)
1596-
tm.assert_frame_equal(result, expected)
1597-
15981417
# axis=0
15991418
result = df.apply(type, axis=0)
16001419
expected = Series({"col1": Series, "col2": Series})

pandas/tests/apply/test_invalid_arg.py

-6
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,6 @@ def test_apply_invalid_axis_value():
4343
df.apply(lambda x: x, 2)
4444

4545

46-
def test_applymap_invalid_na_action(float_frame):
47-
# GH 23803
48-
with pytest.raises(ValueError, match="na_action must be .*Got 'abc'"):
49-
float_frame.applymap(lambda x: len(str(x)), na_action="abc")
50-
51-
5246
def test_agg_raises():
5347
# GH 26513
5448
df = DataFrame({"A": [0, 1], "B": [1, 2]})

0 commit comments

Comments
 (0)