python - 将 apply() 与 Pandas 系列一起使用

标签 python pandas lambda

我有以下代码:

import pandas as pd
frame = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),index=['Utah','Ohio','Texas','Oregon'])

frame

b   d   e
Utah    0.479210    0.161892    -1.315375
Ohio    -0.572543   0.080203    -0.446178
Texas   0.052954    0.043417    0.365056
Oregon  1.462631    0.244453    2.207720

f = lambda x: x.max()-x.min() 
frame.apply(f)

这导致:

b    2.035174
d    0.201035
e    3.523095
dtype: float64

我试图学习如何仅将 lambda 应用于特定列,因此我只想将 lambda 应用于“d”列。这就是我所做的

frame['d'].apply(f)

但它会导致错误: AttributeError: 'float' 对象没有属性 'max'

type(frame['d'])
pandas.core.series.Series

frame['d'].dtype
dtype('float64')

我尝试调试它。看起来 frame['d'] 是 Series 类型,这个系列中的每个值都是一个 float ,而一个 float 没有最小/最大属性。

我以为我只是错过了一些简单的东西,但我对 Python 和 Pandas 的有限了解让我很难过。我如何才能将 lambda 仅应用于“d”列?

最佳答案

问题是 .apply 对一个 Series 有效 elementwise,在一个 DataFrame 中它按 series按行。如果你真的想以这种方式使用 .apply,你可以像这样子集:

In [9]: frame.loc[:,['d']]
Out[9]: 
               d
Utah    2.259488
Ohio    0.458926
Texas  -0.072635
Oregon  0.470217

In [10]: type(frame.loc[:,['d']])
Out[10]: pandas.core.frame.DataFrame

返回一个DataFrame。那么你可以简单地做:

In [11]: frame.loc[:,['d']].apply(lambda x: x.max()-x.min())
Out[11]: 
d    2.332124
dtype: float64

请注意,为简洁起见,您可以简单地使用 frame[['d']],但这更有意义:

In [12]: frame.d.max() - frame.d.min()
Out[12]: 2.3321235565383334

ETA:事实上,即使是整个DataFrame,在这种情况下你真的不需要apply,它肯定会比下面的慢:

In [19]: frame.max() - frame.min()
Out[19]: 
b    3.337040
d    2.332124
e    2.224037
dtype: float64

关于python - 将 apply() 与 Pandas 系列一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553866/

相关文章:

python - 无法通过简单地返回原生异步协程来链接它们

c++ - 使用 lambda 作为试运行选项正常吗?

c++ - 有没有一种方法可以在不捕获 lambda 变量的情况下编写更短的代码?

python - 使用 PyTorch 根据我从张量计算的数字来调整张量矩阵值?

python - 从 Pandas 数据框的列中提取主题标签

python - 从 Python 中的文件中读取随机行,这些行在其他 4 行通过之前不会重复

Python Pandas : Stack and Enumerate Date to Create New Records

python - 将 numpy 数组存储在 pandas 数据框的多个单元格中(Python)

pandas - 如何填充 Pandas Pivot_table 中的索引

c# - 如何使用 Expression 使用 Where 和 OR 构建动态查询