【Pandas】pandas DataFrame apply

Pandas2.2 DataFrame

Function application, GroupBy & window

方法描述
DataFrame.apply(func[, axis, raw, …])用于沿 DataFrame 的轴(行或列)应用一个函数

pandas.DataFrame.apply()

pandas.DataFrame.apply() 是一个非常强大的函数,用于沿 DataFrame 的轴(行或列)应用一个函数。它允许用户自定义函数来处理数据。


方法签名
DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), by_row='compat', engine='python', engine_kwargs=None, **kwargs)

参数说明
参数类型描述
funcfunction应用在 DataFrame 每一行或每一列上的函数。
axis{0 or ‘index’, 1 or ‘columns’}, default: 0若为 0,函数应用于每一列;若为 1,函数应用于每一行。
rawbool, default: False如果为 True,则将行或列作为 NumPy 数组传入函数。否则作为 Series。
result_type{‘expand’, ‘reduce’, ‘broadcast’, None}, default: None控制结果的返回形式。仅当 axis=1 时有效。
argstuple传递给 func 的位置参数。
by_rowstr已弃用,保留用于兼容性。
engine{‘python’}, default: ‘python’执行引擎,当前只支持 Python。
engine_kwargsdict, optional传递给引擎的关键字参数。
**kwargs任意关键字参数会传递给 func

返回值
  • 如果 func 返回标量,则返回一个 Series
  • 如果 func 返回数组,则返回一个 DataFrame

示例
示例1:按列计算平均值(默认 axis=0)
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# 计算每列的平均值
result = df.apply(lambda x: x.mean())
print(result)

输出:

A    2.0
B    5.0
dtype: float64

示例2:按行求和(axis=1)
# 对每一行求和
result = df.apply(lambda x: x.sum(), axis=1)
print(result)

输出:

0    5
1    7
2    9
dtype: int64

示例3:使用 raw=True 将行转为 NumPy 数组
# 使用 NumPy 数组进行操作
result = df.apply(lambda x: x[0] + x[1], axis=1, raw=True)
print(result)

输出:

0    5
1    7
2    9
dtype: int64

示例4:使用 result_type='expand' 展开多个返回值
# 返回多个值并展开成多列
def my_func(row):
    return row['A'] * 2, row['B'] * 3

result = df.apply(my_func, axis=1, result_type='expand')
print(result)

输出:

   0   1
0  2  12
1  4  15
2  6  18

总结
  • apply() 可以对 DataFrame 的行或列执行任意函数。
  • 支持灵活的参数传递和结果处理。
  • 常用于数据清洗、转换、特征工程等场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liuweidong0802

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值