Pandas中的appy和applymap

apply

我们经常会遇到对某一行的数据进行处理或者某一列进行处理这时候我们就可用到pandasapply函数
示例代码:

import pandas as pd
import numpy as np
# 创建一个dataframe 
df = pd.DataFrame(np.random.randn(3,4),columns=['a','b','c','d'])
df
# 生成均值(μ)为0,标准差(σ)为1的标准正态分布的dataframe 3行4列
			a			b			c			d
0	0.982775	1.243378	1.027592	1.207008
1	-1.120674	-0.542617	-0.758449	1.097887
2	-0.236729	-0.038811	0.871838	-0.170809

# apply 内有两个主要参数
# func 要再每一行或者列要应用的功能函数
# axis 指定再行或者列应用该函数

# 对列进行取最大值 
# axis=0 以水平线为参照线 将函数应用到列上
df.apply(lambda x:x.max(),axis=0)

a    0.982775
b    1.243378
c    1.027592
d    1.207008
dtype: float64

# 对行进行取最大值
# axis=1 以铅锤线为参照线 将函数应用到 行
df.apply(lambda x:x.max(),axis=1)

0    1.243378
1    1.097887
2    0.871838
dtype: float64

applymap

applymap则是将函数应用到每一个值
示例代码:

import pandas as pd
import numpy as np
# 创建一个dataframe 
df = pd.DataFrame(np.random.randn(3,4),columns=['a','b','c','d'])
df
# 生成均值(μ)为0,标准差(σ)为1的标准正态分布的dataframe 3行4列
			a			b			c			d
0	0.982775	1.243378	1.027592	1.207008
1	-1.120674	-0.542617	-0.758449	1.097887
2	-0.236729	-0.038811	0.871838	-0.170809

# applymap 
# 我们通常用其中的func参数 同apply
# 将dataframe中的每一数字保留两位小数
df.applymap(lambda x:'%.2f'%x)

	a		b		c		d
0	0.98	1.24	1.03	1.21
1	-1.12	-0.54	-0.76	1.10
2	-0.24	-0.04	0.87	-0.17
发布了21 篇原创文章 · 获赞 12 · 访问量 441

猜你喜欢

转载自blog.csdn.net/weixin_44984627/article/details/104794950