Skip to main content
 首页 » 编程设计

python之pandas 数据框上的 apply 函数可以生成标量吗

2024年10月01日24lidabo

我阅读了有关 Pandas apply 函数的文档,其中指出 apply 函数适用于数据框的行或列并返回一个系列或数据框。是否可以以返回标量的方式编写代码?或者是否有必要进一步链接一个 .pipe 函数。我尝试在文档中提供的示例数据框上编写以下函数:

df = pd.DataFrame({'one' : pd.Series(np.random.randn(3), index=['a', 'b', 'c']), 
    'two' : pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']), 
    'three' : pd.Series(np.random.randn(3), index=['b', 'c', 'd'])}) 
 
def my_func1(x): 
    min_of_x = x[['one', 'two']] 
    return min_of_x['one'] 
 
def my_func2(x): 
    min_of_x = x[['one', 'two']] 
    return min_of_x['one'].iloc[0] 
 
def my_func3(x): 
    min_of_x = x[['one', 'two']] 
    return min_of_x.max() 
 
def my_func4(x, elem_pos=0): 
    return x.iloc[elem_pos] 

当我运行时:

df.apply(my_func1, axis=1) 

它工作正常,并按预期为我提供了一个系列。但是假设我想要第一个元素,或者就此而言,需要对 Series 值进行一些计算以生成标量:

df.apply(my_func2, axis=1) 

我收到错误“AttributeError: ("'numpy.float64' object has no attribute 'iloc'", 'occurred at index a')”。如果我使用计算最大值的 my_func3:

df.apply(my_func3, axis=1) 

返回一个系列又可以正常工作了。返回标量的唯一方法似乎是使用 .pipe 链接另一个函数:

df.apply(my_func1, axis=1).pipe(my_func4, 2) 

所以我只是想得出结论,apply 函数是只生成一个 Series 还是一个 DataFrame,任何返回另一个值的尝试都会产生这个错误。会是这样吗?这只是为了以防万一我想对结果进行一些计算,而内置的 Panda 和 NumPy 函数无法完成。

请您参考如下方法:

要了解的基本内容是pd.Series 对象总是 传递给apply。通过什么取决于您调用它的轴。

例如,axis=1 将传递这个:

one      ... 
three    ... 
two      ... 
Name: a/b/c/d, dtype: float64 

并且,axis=0 将传递:

a    ... 
b    ... 
c    ... 
d    ... 
dtype: float64 

无论哪种情况,这都是一个 pd.Series 对象。

在 my_func1 中,您可以像这样对系列进行切片:x[['one', 'two']] 这也会生成一个系列对象。索引单个项目,如 x['one'] 将返回一个 float 对象,因此 float 对象不会返回自然是有道理的有一个 .iloc 属性与之关联。这就是 my_func2 抛出 AttributeError 的原因。


作为练习,尝试运行这段代码:

In [891]: def my_func1(x): 
     ...:     print(type(x['one'])) 
     ...:     min_of_x = x[['one', 'two']] 
     ...:     return min_of_x['one'] 
 
In [892]: df.apply(my_func1, axis=1) 

这给出:

<class 'numpy.float64'> 
<class 'numpy.float64'> 
<class 'numpy.float64'> 
<class 'numpy.float64'>