• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

python中 apply()函数的用法

函数格式为:apply(func,*args,**kwargs)

用途:当一个函数的参数存在于一个元组或者一个字典中时,用来间接的调用这个函数,并肩元组或者字典中的参数按照顺序传递给参数

解析:args是一个包含按照函数所需参数传递的位置参数的一个元组,是不是很拗口,意思就是,假如A函数的函数位置为 A(a=1,b=2),那么这个元组中就必须严格按照这个参数的位置顺序进行传递(a=3,b=4),而不能是(b=4,a=3)这样的顺序
kwargs是一个包含关键字参数的字典,而其中args如果不传递,kwargs需要传递,则必须在args的位置留空

apply的返回值就是函数func函数的返回值

   def function(a,b):  
        print(a,b)  
    apply(function,('good','better'))  
    apply(function,(2,3+6))  
    apply(function,('cai','quan'))  
    apply(function,('cai',),{'b':'caiquan'})  
    apply(function,(),{'a':'caiquan','b':'Tom'})  
    #--使用 apply 函数调用基类的构造函数  
    class Rectangle:  
        def __init__(self, color="white", width=10, height=10):  
            print "create a", color, self, "sized", width, "x", height  
      
    class RoundedRectangle(Rectangle):  
        def __init__(self, **kw):  
            apply(Rectangle.__init__, (self,), kw)  
    rect = Rectangle(color="green", height=100, width=100)  
    rect = RoundedRectangle(color="blue", height=20)  

 

输出结果:

('good', 'better')
(2, 9)
('cai', 'quan')
('cai', 'caiquan')
('caiquan', 'Tom')
create a green <__main__.Rectangle instance at 0x0678FA08> sized 100 x 100
create a blue <__main__.RoundedRectangle instance at 0x06620468> sized 10 x 20

apply函数默认的是axis为 axis=0

 

data= [
    [1,2,3],
    [5,4,1],
    [3,2,2]
]
df = pd.DataFrame(data,columns=['A','B','C'])
f = lambda x: (x - np.min(x)) / (np.max(x) - np.min(x))  print(df) A B C 0 1 2 3 1 5 4 1 2 3 2 2

1、axis=1

df1 = df.copy()
df1 = df1.apply(f,axis=1)   #计算的时候取的是行数
df1
         A      B     C
0    0.0    0.50    1.0
1    1.0    0.75    0.0
2    1.0    0.00    0.0

2、axis=2

df2 = df.copy()
df2 = df2.apply(f,axis=0)
df2

         A    B    C
0    0.0    0.0    1.0
1    1.0    1.0    0.0
2    0.5    0.0    0.5

3、默认axis

df3 = df.copy()
df3 = df3.apply(f)
df3   # 在DataFrame中apply函数默认的是axis=0,取的是列数

       A    B    C
0    0.0    0.0    1.0
1    1.0    1.0    0.0
2    0.5    0.0    0.5
(df['A'] - df['A'].min())/(df['A'].max()-df['A'].min())
0    0.0
1    1.0
2    0.5
Name: A, dtype: float64

转载:https://blog.csdn.net/chenyulancn/article/details/40142797

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-04-24 12:00  乐晓东随笔  阅读(68614)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3