Skip to content

Commit

Permalink
fix tests/frame/methods/test_map.py
Browse files Browse the repository at this point in the history
  • Loading branch information
topper-123 committed Apr 7, 2023
1 parent e1c30b8 commit 415414d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,8 @@ Deprecations
- Deprecated :meth:`DataFrame.swapaxes` and :meth:`Series.swapaxes`, use :meth:`DataFrame.transpose` or :meth:`Series.transpose` instead (:issue:`51946`)
- Deprecated making :meth:`Series.apply` return a :class:`DataFrame` when the passed-in callable returns a :class:`Series` object. In the future this will return a :class:`Series` whose values are themselves :class:`Series`. This pattern was very slow and it's recommended to use alternative methods to archive the same goal (:issue:`52116`)
- Deprecated parameter ``convert_type`` in :meth:`Series.apply` (:issue:`52140`)
- Deprecated ``freq`` parameter in :class:`PeriodArray` constructor, pass ``dtype`` instead (:issue:`52462`)
- Deprecated :meth:`DataFrame.applymap`. Use the new :meth:`DataFrame.map` method instead (:issue:`52353`)
- Deprecated ``freq`` parameter in :class:`PeriodArray` constructor, pass ``dtype`` instead (:issue:`52462`)
-

.. ---------------------------------------------------------------------------
Expand Down
53 changes: 31 additions & 22 deletions pandas/tests/frame/methods/test_map.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
import warnings

import numpy as np
import pytest
Expand All @@ -13,21 +14,21 @@
import pandas._testing as tm


def test_applymap(float_frame):
result = float_frame.applymap(lambda x: x * 2)
def test_map(float_frame):
result = float_frame.map(lambda x: x * 2)
tm.assert_frame_equal(result, float_frame * 2)
float_frame.applymap(type)
float_frame.map(type)

# GH 465: function returning tuples
result = float_frame.applymap(lambda x: (x, x))["A"][0]
result = float_frame.map(lambda x: (x, x))["A"][0]
assert isinstance(result, tuple)


@pytest.mark.parametrize("val", [1, 1.0])
def test_applymap_float_object_conversion(val):
# GH 2909: object conversion to float in constructor?
df = DataFrame(data=[val, "a"])
result = df.applymap(lambda x: x).dtypes[0]
result = df.map(lambda x: x).dtypes[0]
assert result == object


Expand All @@ -41,15 +42,15 @@ def test_applymap_keeps_dtype(na_action):
def func(x):
return str.upper(x) if not pd.isna(x) else x

result = df.applymap(func, na_action=na_action)
result = df.map(func, na_action=na_action)

expected_sparse = pd.array(["A", np.nan, "B"], dtype=pd.SparseDtype(object))
expected_arr = expected_sparse.astype(object)
expected = DataFrame({"a": expected_arr, "b": expected_sparse})

tm.assert_frame_equal(result, expected)

result_empty = df.iloc[:0, :].applymap(func, na_action=na_action)
result_empty = df.iloc[:0, :].map(func, na_action=na_action)
expected_empty = expected.iloc[:0, :]
tm.assert_frame_equal(result_empty, expected_empty)

Expand All @@ -61,9 +62,9 @@ def test_applymap_str():
cols = ["a", "a", "a", "a"]
df.columns = cols

expected = df2.applymap(str)
expected = df2.map(str)
expected.columns = cols
result = df.applymap(str)
result = df.map(str)
tm.assert_frame_equal(result, expected)


Expand All @@ -75,7 +76,7 @@ def test_applymap_datetimelike(col, val):
# datetime/timedelta
df = DataFrame(np.random.random((3, 4)))
df[col] = val
result = df.applymap(str)
result = df.map(str)
assert result.loc[0, col] == str(df.loc[0, col])


Expand All @@ -91,24 +92,24 @@ def test_applymap_datetimelike(col, val):
@pytest.mark.parametrize("func", [round, lambda x: x])
def test_applymap_empty(expected, func):
# GH 8222
result = expected.applymap(func)
result = expected.map(func)
tm.assert_frame_equal(result, expected)


def test_applymap_kwargs():
# GH 40652
result = DataFrame([[1, 2], [3, 4]]).applymap(lambda x, y: x + y, y=2)
result = DataFrame([[1, 2], [3, 4]]).map(lambda x, y: x + y, y=2)
expected = DataFrame([[3, 4], [5, 6]])
tm.assert_frame_equal(result, expected)


def test_applymap_na_ignore(float_frame):
# GH 23803
strlen_frame = float_frame.applymap(lambda x: len(str(x)))
strlen_frame = float_frame.map(lambda x: len(str(x)))
float_frame_with_na = float_frame.copy()
mask = np.random.randint(0, 2, size=float_frame.shape, dtype=bool)
float_frame_with_na[mask] = pd.NA
strlen_frame_na_ignore = float_frame_with_na.applymap(
strlen_frame_na_ignore = float_frame_with_na.map(
lambda x: len(str(x)), na_action="ignore"
)
strlen_frame_with_na = strlen_frame.copy()
Expand All @@ -124,7 +125,7 @@ def func(x):
return (x.hour, x.day, x.month)

# it works!
DataFrame(ser).applymap(func)
DataFrame(ser).map(func)


def test_applymap_box():
Expand All @@ -144,7 +145,7 @@ def test_applymap_box():
}
)

result = df.applymap(lambda x: type(x).__name__)
result = df.map(lambda x: type(x).__name__)
expected = DataFrame(
{
"a": ["Timestamp", "Timestamp"],
Expand All @@ -161,8 +162,8 @@ def test_frame_applymap_dont_convert_datetime64():

df = DataFrame({"x1": [datetime(1996, 1, 1)]})

df = df.applymap(lambda x: x + BDay())
df = df.applymap(lambda x: x + BDay())
df = df.map(lambda x: x + BDay())
df = df.map(lambda x: x + BDay())

result = df.x1.dtype
assert result == "M8[ns]"
Expand All @@ -182,7 +183,7 @@ def non_reducing_function(val):
for func in [reducing_function, non_reducing_function]:
del values[:]

df.applymap(func)
df.map(func)
assert values == df.a.to_list()


Expand All @@ -193,15 +194,23 @@ def test_applymap_type():
index=["a", "b", "c"],
)

result = df.applymap(type)
result = df.map(type)
expected = DataFrame(
{"col1": [int, str, type], "col2": [float, datetime, float]},
index=["a", "b", "c"],
)
tm.assert_frame_equal(result, expected)


def test_applymap_invalid_na_action(float_frame):
def test_map_invalid_na_action(float_frame):
# GH 23803
with pytest.raises(ValueError, match="na_action must be .*Got 'abc'"):
float_frame.applymap(lambda x: len(str(x)), na_action="abc")
float_frame.map(lambda x: len(str(x)), na_action="abc")


def test_applymap_deprecated():
# GH52353
df = DataFrame({"a": [1, 2, 3]})
msg = "DataFrame.applymap has been deprecated. Use DataFrame.map instead."
with tm.assert_produces_warning(FutureWarning, match=msg):
df.applymap(lambda x: x)

0 comments on commit 415414d

Please sign in to comment.