- 一、apply用法
- 二、map用法
- apply和map的区别
一、apply用法概括:
apply:用在dataframe上,用于对row或者column进行计算
applymap :用于dataframe上,是元素级别的操作
map(python自带):用于series上,是元素级别的操作
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) # out: a b c d 0 6 4 9 5 1 9 1 9 9 2 4 5 2 8 3 0 3 8 7 # 作用在一列上 axis=0表示作用于列 不填默认为0 r1 = df.apply(lambda x: x.max() - x.min(), axis=0) print(r1) # out: a 9 b 4 c 7 d 4 dtype: int64 r2 = df.apply(lambda x: x.max() - x.min()) print(r2) # out: a 9 b 4 c 7 d 4 dtype: int64 # 作用在一行上 r3 = df.apply(lambda x: x.max() - x.min(), axis=1) print(r3) # out: 0 5 1 8 2 6 3 8 dtype: int64
拓展:applymap: 作用在dataframe的每一个元素上
r4 = df.applymap(lambda x: str(x)+'s')
print(r4)
# out:
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) # map返回值为object 需转为list可视化 print(list(r)) # out: [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])
# 使用apply处理
data['date'] = data['date'].apply(lambda x: str(x).split(' ')[0])
print(data['date'])
# 使用map处理
data['date'] = list(map(lambda x: str(x).split(' ')[0], list(data['date'])))
print(data['date'])



