pandas.DataFrame.apply#
- DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)[源代码]#
沿DataFrame的轴应用函数。
传递给函数的对象是其索引为DataFrame的索引的Series对象 (
axis=0
)或DataFrame的列 (axis=1
)。默认情况下 (result_type=None
),则从所应用函数的返回类型推断最终的返回类型。否则,它取决于 result_type 论点。- 参数
- func功能
函数应用于每一列或每行。
- axis{0或‘index’,1或‘Columns’},默认为0
沿其应用函数的轴:
0或‘index’:将函数应用于每一列。
1或‘Columns’:对每行应用函数。
- raw布尔值,默认为False
确定是将行还是列作为Series或ndarray对象传递:
False
:将每行或每列作为Series传递给函数。True
:传递的函数将改为接收ndarray对象。如果您只是应用NumPy缩减函数,这将获得更好的性能。
- result_type{‘扩展’,‘减少’,‘广播’,无},默认为无
这些仅在以下情况下才会起作用
axis=1
(专栏):‘Expand’:类似列表的结果将变成列。
‘Reduced’:如果可能,返回一个Series,而不是展开类似列表的结果。这是‘扩展’的反义词。
广播:结果将被广播到DataFrame的原始形状,原始索引和列将被保留。
默认行为(None)取决于应用函数的返回值:类似列表的结果将作为一系列结果返回。但是,如果Apply函数返回一个Series,则这些列将展开为列。
- args元组
要传递到的位置参数 func 除了阵列/系列之外。
- **kwargs
要作为关键字参数传递到的其他关键字参数 func 。
- 退货
- 系列或DataFrame
申请结果
func
沿DataFrame的给定轴。
参见
DataFrame.applymap
用于元素级运算。
DataFrame.aggregate
仅执行聚合类型操作。
DataFrame.transform
仅执行转换类型操作。
注意事项
改变传递的对象的函数可能会产生意外的行为或错误,因此不受支持。看见 使用用户定义函数(UDF)方法进行变异 了解更多详细信息。
示例
>>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B']) >>> df A B 0 4 9 1 4 9 2 4 9
使用NumPy通用函数(在本例中与
np.sqrt(df)
):>>> df.apply(np.sqrt) A B 0 2.0 3.0 1 2.0 3.0 2 2.0 3.0
在任一轴上使用缩减函数
>>> df.apply(np.sum, axis=0) A 12 B 27 dtype: int64
>>> df.apply(np.sum, axis=1) 0 13 1 13 2 13 dtype: int64
返回一个类似列表的结果将导致一系列
>>> df.apply(lambda x: [1, 2], axis=1) 0 [1, 2] 1 [1, 2] 2 [1, 2] dtype: object
通过
result_type='expand'
将类似列表的结果扩展到数据帧的列>>> df.apply(lambda x: [1, 2], axis=1, result_type='expand') 0 1 0 1 2 1 1 2 2 1 2
在函数内部返回序列类似于传递
result_type='expand'
。得到的列名将是Series索引。>>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1) foo bar 0 1 2 1 1 2 2 1 2
通过
result_type='broadcast'
将确保相同的形状结果,无论函数返回的是列表形式还是标量形式,并沿轴广播。生成的列名将是原始列名。>>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast') A B 0 1 2 1 1 2 2 1 2