python - 如何传递一系列来调用用户定义的函数?

标签 python user-defined-functions

我试图将一系列传递给用户定义的函数并收到此错误:

功能:

def scale(series):
   sc=StandardScaler()
   sc.fit_transform(series)
   print(series)

调用代码:

df['Value'].apply(scale) # df['Value'] is a Series having float dtype.

错误:

ValueError: Expected 2D array, got scalar array instead:
array=28.69.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

谁能帮忙解决这个问题吗?

最佳答案

方法apply会将函数应用于Series中的每个元素(或者在DataFrame的情况下,每行或每列取决于所选轴)。在这里,您希望函数处理整个 Series 并输出一个新的 Series

因此,您可以简单地运行:

StandardScaler().fit_transform(df['Value'].values.reshape(-1, 1))

StandardScaler 不使用 2D 数组作为输入,其中每一行都是由一个或多个特征组成的示例输入。即使它只是一个单一的特征(就像你的例子中的情况一样),它也必须有正确的尺寸。因此,在将您的Series移交给sklearn之前,我将访问这些值(numpy表示)并相应地对其进行 reshape 。

有关reshape(-1, ...)的更多详细信息,请查看:What does -1 mean in numpy reshape?

现在,最好的一点。如果您的整个 DataFrame 由一列组成,您只需执行以下操作:

StandardScaler().fit_transform(df)

即使没有,您仍然可以避免 reshape :

StandardScaler().fit_transform(df[['Value']])

请注意,在这种情况下,'Value' 是如何被 2 组大括号包围的,因此这次它不是一个 Series 而是一个 DataFrame > 使用原始列的子集(如果您不想缩放所有列)。由于 DataFrame 已经是二维的,因此您无需担心 reshape 。

最后,如果您只想缩放某些列并更新原始 DataFrame,您所要做的就是:

>>> df = pd.DataFrame({'A': [1,2,3], 'B': [0,5,6], 'C': [7, 8, 9]})
>>> columns_to_scale = ['A', 'B']
>>> df[columns_to_scale] = StandardScaler().fit_transform(df[columns_to_scale])
>>> df
          A         B  C
0 -1.224745 -1.397001  7
1  0.000000  0.508001  8
2  1.224745  0.889001  9

关于python - 如何传递一系列来调用用户定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68055495/

相关文章:

python - 递归遍历一个2d二进制数组并统计“"1'”的个数经过

python - 自定义 Python unicode 模块

Python私有(private)方法供公共(public)使用

java - 调用没有对象或传递值的函数

c - 在 C 中,如何从用户定义的函数中获取值,然后在另一个用户定义的函数中打印出来?

excel - vba sumifs 对日期感到困惑,四月的错误结果

python - 为什么这个函数返回 3125

python - Numba 函数比 C++ 慢,循环重新排序进一步减慢 x10

sql - 从记录类型的单列中拆分/提取值,将用户定义的函数应用于多行 CTE

python - 使用函数打破 while 循环