apply、map、applymap有什么区别?

中等机器学习

答题要点

# map:Series级别,一一映射
df['gender_cn'] = df['gender'].map({'M': '男', 'F': '女'})
df['age_group'] = df['age'].map(lambda x: '青年' if x < 30 else '中年')

# apply:Series或DataFrame级别
df['age'].apply(lambda x: x * 2)          # Series
df.apply(lambda x: x.max() - x.min())     # 每列
df.apply(lambda x: x['price'] * x['qty'], axis=1)  # 每行

# applymap:DataFrame所有元素(已过时,用map)
df.map(lambda x: f'{x:.2f}')              # Pandas 2.1+
df.applymap(lambda x: f'{x:.2f}')         # 旧版本

# 带参数的apply
def calculate_tax(price, rate=0.1):
    return price * rate
df['tax'] = df['price'].apply(calculate_tax, rate=0.13)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题