pandas函数映射
import pandas as pd
import numpy as np
from pandas import Series,DataFrame
df1 = DataFrame(
np.random.choice(range(20),size=(4,3),replace=False),
index=list('ABCD'),
columns=list('abc')
)
print(df1)
#使用numpy函数操作 axis 控制行列聚合 0跨列 1跨行
print(np.sum(df1,axis=1))
#平均
print(np.mean(df1,axis=1))
#整体的极差
print(np.ptp(df1))
#最大值
print(np.max(df1))
#每一行的极差
print(np.max(df1,axis=1)-np.min(df1,axis=1))
'''
!!!!!!!!!!!!!
object.apply(func,axis=0/1)
对某obj的行或列 应用一个函数 func
'''
def Myptp(x):
return x.max()-x.min()
print(df1.apply(Myptp,axis=1))
#使用匿名函数
print(df1.apply(lambda x:x.max()-x.min(),axis=1))
#省略小数位数
df2 = DataFrame(
np.random.randn(4,3),
index=list('ABCD'),
columns=list('一二三')
)
print(df2)
print(df2.apply(lambda x:round(x,2)))
print(round(df2,2))
'''
applymap(func)把 func 应用到每个元素上
'''
print(df2.applymap(lambda x:f'{round(x,2)}%'))
标签:函数,映射,df1,df2,np,print,pandas,axis
From: https://www.cnblogs.com/mengdie1978/p/17880113.html