我试图将一系列传递给用户定义的函数并收到此错误:
功能:
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/