如何编辑我的代码,以便梯度函数的应用列中只有一个数字?

问题描述 投票:0回答:1

所以我有一个包含 NaN 值的数据框,我将它们替换为 0(您将在下面看到)。 我尝试计算每行的 np.gradient 。我将输出应用到一个新列,但该列中有多个值。 此后我想列出梯度为负的索引。

# Replace NaN values with 0
df.fillna(0, inplace=True)

# Function to calculate gradient per row
def calculate_gradient(row):
    gradient = np.gradient(row)
    return gradient

# Apply the function row-wise and add the result to a new column
df['Gradient'] = df.apply(calculate_gradient, axis=1)

#list the index where the gradient column is negative 
negative_gradient_indices = [df['Gradient'] < 0].index.tolist()

print(negative_gradient_indices)

Picture of output: Gradient column with multiple outputs

我期待整行有一个单一的渐变。当我列出索引时,错误指出它包含多个元素。

python dataframe numpy nan numpy-ufunc
1个回答
0
投票

我假设您想计算数据帧的完整列的梯度。

我设计了一个如下所示的数据框:

df = pd.DataFrame(data=[2, 6, 6, np.NaN, 5], columns=['data'])

然后您可以将函数应用到列上并获得结果:

# Apply the function row-wise and add the result to a new column
df['Gradient'] = calculate_gradient(df['data'])

# list the index where the gradient column is negative
negative_gradient_indices = df.index[df['Gradient'] < 0].to_list()

输出:

[2, 3]
© www.soinside.com 2019 - 2024. All rights reserved.