Python中apply和map的区别

文章目录

概括:
apply:用在dataframe上,用于对row或者column进行计算
applymap :用于dataframe上,是元素级别的操作
map(python自带):用于series上,是元素级别的操作

一、apply用法

apply作用于dataframe的一行或一列上

from pandas import DataFrame
import numpy as np

df = DataFrame(data=np.random.randint(0, 10, size=(4, 4)), columns=['a', 'b', 'c', 'd'])
print(df)

   a  b  c  d
0  6  4  9  5
1  9  1  9  9
2  4  5  2  8
3  0  3  8  7

r1 = df.apply(lambda x: x.max() - x.min(), axis=0)
print(r1)

a    9
b    4
c    7
d    4
dtype: int64

r2 = df.apply(lambda x: x.max() - x.min())
print(r2)

a    9
b    4
c    7
d    4
dtype: int64

r3 = df.apply(lambda x: x.max() - x.min(), axis=1)
print(r3)

0    5
1    8
2    6
3    8
dtype: int64

拓展:applymap: 作用在dataframe的每一个元素上

r4 = df.applymap(lambda x: str(x)+'s')
print(r4)

    a   b   c   d
0  6s  4s  9s  5s
1  9s  1s  9s  9s
2  4s  5s  2s  8s
3  0s  3s  8s  7s

二、map用法

map会根据提供的函数对指定序列做映射
map(function, sequence,…)

l = [1, 2, 3, 4, 5]
r = map(lambda x: x*2, l)

print(list(r))

[2, 4, 6, 8, 10]

apply和map的区别

可以通俗的理解apply和map都为数据集迭代加工的方法
apply用在dataframe上,而map用于常规一维数据处理
使用map也可以处理dataframe数据只是会显得很冗余

  • 针对电影评论数据,做日期格式处理,两种方法比较
import pandas as pd

filepath = "movie.csv"
data = pd.read_csv(filepath, names=["author", "comment", "date"], usecols=[0, 1, 2])

data['date'] = data['date'].apply(lambda x: str(x).split(' ')[0])
print(data['date'])

data['date'] = list(map(lambda x: str(x).split(' ')[0], list(data['date'])))
print(data['date'])

Original: https://blog.csdn.net/qq_44718932/article/details/120823745
Author: PENG越
Title: Python中apply和map的区别

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/674508/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球