# 5种利用自定义函数批量处理元素方法介绍
# 导入相关的库和包
import numpy as np
import pandas as pd
from pandas import Dataframe, Series
#1.python内置的map函数
lst = [1,2,3]
f = lambda x: x * 10
lst2 = list(map(f, lst))
np.disp(lst2) # 显示元素
[10, 20, 30]
#2.Series中的map函数
# 和python中的map相似 只不过输入Series的一个方法
series = Series([1,2,3])
f2 = lambda x: "%.2f" %x
np.disp(series.map(f2)) # 设置格式
0 1.00
1 2.00
2 3.00
dtype: object
#3.Series中的apply函数
# 自由度更高的一种
np.disp(series.apply(f2))
0 1.00
1 2.00
2 3.00
dtype: object
#4.Dataframe中的apply函数
"""
func:传入的函数,多为自定义的lambda函数
axis:可以指定对行或者列的操作 默认为沿着行的方向(axis='index'/0)
raw:以Series的方式传入False(default)还是转换成ndarray(True)再传入
"""
frame = pd.Dataframe(np.arange(12.).reshape((4, 3)),
columns=list('bde'),
index=['Utah', 'Ohio', 'Texas', 'Oregon'])
frame.apply(lambda x: min(x), axis='index', raw=True) # 计算每列的最小值
# 其返回值不一定是一个标量 也可以生成一个dataframe 但要构建新的Series
def f(x):
return pd.Series([x.min(), x.max()], index=['min', 'max'])
frame.apply(f, axis=0) # 对每一个列都返回一个Series 索引为行
| b | d | e |
|---|
| min | 0.0 | 1.0 | 2.0 |
|---|
| max | 9.0 | 10.0 | 11.0 |
|---|
#5.Dataframe中的applymap函
"""
为了和Series中的map区别开 applymap是元素级函数 操作frame中的每个元素
在函数定义时 就不再是apply那样以一个Series传入了 而是一个single value
在定义函数时要注意不要使用sum、min等这样只针对Series适用的函数
"""
frame.applymap(lambda x: '%.2f' %x) # 逐元素操作
| b | d | e |
|---|
| Utah | 0.00 | 1.00 | 2.00 |
|---|
| Ohio | 3.00 | 4.00 | 5.00 |
|---|
| Texas | 6.00 | 7.00 | 8.00 |
|---|
| Oregon | 9.00 | 10.00 | 11.00 |
|---|