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)
参数说明
参数 | 类型 | 描述 |
---|---|---|
func | function | 应用在 DataFrame 每一行或每一列上的函数。 |
axis | {0 or ‘index’, 1 or ‘columns’}, default: 0 | 若为 0 ,函数应用于每一列;若为 1 ,函数应用于每一行。 |
raw | bool, default: False | 如果为 True ,则将行或列作为 NumPy 数组传入函数。否则作为 Series。 |
result_type | {‘expand’, ‘reduce’, ‘broadcast’, None}, default: None | 控制结果的返回形式。仅当 axis=1 时有效。 |
args | tuple | 传递给 func 的位置参数。 |
by_row | str | 已弃用,保留用于兼容性。 |
engine | {‘python’}, default: ‘python’ | 执行引擎,当前只支持 Python。 |
engine_kwargs | dict, 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 的行或列执行任意函数。- 支持灵活的参数传递和结果处理。
- 常用于数据清洗、转换、特征工程等场景。