pandas37 df.apply沿轴应用函数(作用于每一列或行 tcy)

1.函数

df.apply(func, axis=0, broadcast=None, raw=False,
         reduce=None, result_type=None, args=(), **kwds)# 沿DataFrame的轴应用函数;
s.apply(func, convert_dtype=True, args=(), **kwds)

参数
    func : 应用于每个列或行的函数python函数用标量,np函数用序列
    axis=0:{0或'index',1或'columns'},应用函数的轴
    #     * 0或'index':将函数应用于每列。
    #     * 1或'columns':将函数应用于每一行。
    raw=False:
        *False:将每行或每列作为一个系列传递给函数。
        *True:传递的函数将接收ndarray对象;

    result_type=None:{'expand','reduce','broadcast',None}只在axis = 1列时起作用
        *'expand':列表式结果将变为列。
        *'reduce':返回系列而不是扩展类似列表的结果。这与'expand'相反。
        *'broadcast':结果将广播到原始形状
        *None)列表的结果将作为系列返回
        但是如果apply函数返回一个Series这些被扩展为列。

    args:元组#func位置参数
    ** kwds #func作为关键字参数

2.df实例

# 实例1:用numpy通用函数
df = pd.DataFrame(np.arange(10,19).reshape(3,3), columns=['A', 'B','C'])
df.apply(np.square)#等价于np.square(df)

 # df                   result
     A    B    C       A     B    C
0  10  11  12      0  100  121  144
1  13  14  15      1  169  196  225
2  16  17  18      2  256  289  324

============================================================
# 实例2:axis在任一轴上使用缩小功能
result1=df.apply(np.sum, axis=0)     #结果同下
result1=df.apply(np.sum,raw=True)    #df作为ndarray数组传入,性能提升
result2=df.apply(np.sum, axis=1)

# df               result1      result2
    A   B   C      A    39      0    33
0  10  11  12      B    42      1    42
1  13  14  15      C    45      2    51
2  16  17  18      dtype: int64      dtype: int64

============================================================
# 实例3.1:重新调整类似列表将导致系列
result1=df.apply(lambda x: [1, 2])
result2=df.apply(lambda x: [1, 2], axis=1)

# 实例3.2:result_type ='expand'将扩展列表数据到df的列中
result3=df.apply(lambda x: [1, 2], axis=1, result_type='expand')

# 实例3.3:result_type='expand'将系列数据作为df的列,列名为序列索引
result4=df.apply(lambda x: pd.Series([1, 2], index=['A', 'B']), axis=1)

# 实例3.4:result_type ='broadcast'``确保相同形状
# 函数返回列表或标量,并沿轴播放
result5=df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')

# result1          result2        result3    result4    result5
                        
A    [1, 2]          0 [1, 2]         0 1        A B        A B
B    [1, 2]          1 [1, 2]       0 1 2      0 1 2      0 1 2
C    [1, 2]          2 [1, 2]       1 1 2      1 1 2      1 1 2
dtype: object dtype: object         2 1 2      2 1 2      2 1 2

============================================================
# 实例4:函数参数
def add(x=0,y=0,z=0):
    return x+y+z
arg_dict={'y':df.A,'z':df.B}

df.apply(add,args=(2,3))         #将df的每一列+2+3
df.apply(add,args=(df.A,df.B))   #将df的每一列+A列+B列=A=2*A+B;B= A+2*B ;C=A+B+C
df.apply(add, axis=0, broadcast=None, raw=False,
         reduce=None, result_type=None, args=(),**arg_dict)     #结果同上
df.apply(add, axis=0, broadcast=None, raw=False,
         reduce=None, result_type=None, args=(),y=df.A,z=df.B)  #结果同上

3.系列实例

# 实例5.1:Series序列应用
s=pd.Series([1,2,3],name='name')
def adder(x, y):
    return np.add(x, y)

s.apply(np.log)                      # 库函数
result1=s.apply(lambda x: x + 2)     # lambda函数
result1=s.apply(adder, args=(2,))    # 自定义函数

0    3
1    4
2    5
Name: name, dtype: int64

# 实例5.2:
def sum(x, **kwargs):
    for month in kwargs:
        x += kwargs[month]
    return x

s.apply(sum, a1=1, a2=2, a3=3)  # 多参数

0    7
1    8
2    9
Name: name, dtype: int64

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值