Difference between map, applymap and apply methods in Pandas

前端 未结 10 1676
刺人心
刺人心 2020-11-22 03:00

Can you tell me when to use these vectorization methods with basic examples?

I see that map is a Series method whereas the rest are

10条回答
  •  误落风尘
    2020-11-22 03:09

    Comparing map, applymap and apply: Context Matters

    First major difference: DEFINITION

    • map is defined on Series ONLY
    • applymap is defined on DataFrames ONLY
    • apply is defined on BOTH

    Second major difference: INPUT ARGUMENT

    • map accepts dicts, Series, or callable
    • applymap and apply accept callables only

    Third major difference: BEHAVIOR

    • map is elementwise for Series
    • applymap is elementwise for DataFrames
    • apply also works elementwise but is suited to more complex operations and aggregation. The behaviour and return value depends on the function.

    Fourth major difference (the most important one): USE CASE

    • map is meant for mapping values from one domain to another, so is optimised for performance (e.g., df['A'].map({1:'a', 2:'b', 3:'c'}))
    • applymap is good for elementwise transformations across multiple rows/columns (e.g., df[['A', 'B', 'C']].applymap(str.strip))
    • apply is for applying any function that cannot be vectorised (e.g., df['sentences'].apply(nltk.sent_tokenize))

    Summarising

    Footnotes

    1. map when passed a dictionary/Series will map elements based on the keys in that dictionary/Series. Missing values will be recorded as NaN in the output.
    2. applymap in more recent versions has been optimised for some operations. You will find applymap slightly faster than apply in some cases. My suggestion is to test them both and use whatever works better.

    3. map is optimised for elementwise mappings and transformation. Operations that involve dictionaries or Series will enable pandas to use faster code paths for better performance.

    4. Series.apply returns a scalar for aggregating operations, Series otherwise. Similarly for DataFrame.apply. Note that apply also has fastpaths when called with certain NumPy functions such as mean, sum, etc.

提交回复
热议问题