pd.apply--对数据表应用函数

本文详细介绍了Pandas库中DataFrame.apply()函数的使用方法,包括其参数设置、返回值类型及应用场景。通过实例展示了如何利用该函数进行数据聚合运算,实现对DataFrame列或行的自定义操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DataFrame.apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds)API

用于 DataFrame 和 Series 对象。主要用于数据聚合运算,可以很方便的对分组进行现有的运算和自定义的运算。

返回:Series or DataFrame

参数:
func:函数,可应用于每个列或行。
axis=0:{0 or ‘index’, 1 or ‘columns’}, default 0 函数所应用的轴,0 or ‘index’: 列,1 or ‘columns’: 行
raw=False:bool, default False。
result_type:{‘expand’, ‘reduce’, ‘broadcast’, None}, default None。只在axis 为列时起作用
‘expand’ : list-like results will be turned into columns.
‘reduce’ : returns a Series if possible rather than expanding list-like results. This is the opposite of ‘expand’.
‘broadcast’ : results will be broadcast to the original shape of the DataFrame, the original index and columns will be retained.
The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns.

arg:stuple
Positional arguments to pass to func in addition to the array/series.

df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
df
   A  B
0  4  9
1  4  9
2  4  9   
df.apply(np.sqrt)
     A    B
0  2.0  3.0
1  2.0  3.0
2  2.0  3.0
df.apply(lambda x: [1, 2], axis=1, result_type='expand')
   0  1
0  1  2
1  1  2
2  1  2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值