pandas-dev / pandas

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
https://pandas.pydata.org
BSD 3-Clause "New" or "Revised" License
42.57k stars 17.56k forks source link

ENH: is it possible to save a reference to a method depending on the version #59138

Closed quant12345 closed 2 days ago

quant12345 commented 2 days ago

Feature Type

Problem Description

I did the PR. Based on the version, map or applymap is selected. This requires additional lines of code. Depending on the version, is it possible to save the link to a variable and use it instead of map, applymap?

Feature Description

Select map or applymap depending on the version of pandas.

Alternative Solutions

Pseudocode:

PANDAS_VERSION = Version(pd.__version__)
PANDAS_210 = PANDAS_VERSION >= Version("2.1.0")

select_map = ''

if PANDAS_210:
   select_map = map
else:
   select_map = applymap

df.select_map(lambda x: len(str(x)))

Additional Context

No response

Aloqeely commented 2 days ago

Thanks for opening the issue. This seems more like a usage question which should be asked on Stack overflow instead.

But, to answer your question, yes you can do that by using getattr, the implementation would look something like this:

PANDAS_VERSION = Version(pd.__version__)
PANDAS_210 = PANDAS_VERSION >= Version("2.1.0")

select_map = 'map'

if not PANDAS_210:
   select_map = 'applymap'

getattr(df, select_map)(lambda x: len(str(x)))
Aloqeely commented 2 days ago

Another implementation would be to rely on hasattr instead of checking the pandas version, something like:

if hasattr(df, "map"):
    df.map(lambda x: len(str(x)))
else:
    df.applymap(lambda x: len(str(x)))

Feel free to choose whichever method you like!

quant12345 commented 2 days ago

@Aloqeely thank you. The first is what need.