How do I edit my code so that there will only be a single number in the gradient function’s applied column?

  Kiến thức lập trình

So I have a dataframe with NaN values and I replaced them with 0 (you will see below).
I tried to calculated the np.gradient per row. I applied the output to a new column, but the column has multiple values in it.
Thereafter I wanted to list the index for where the gradient is negative.

# 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)

I was expecting a singular gradient for the whole row. When I list the index the error states that it contains more than one element.

New contributor

Tania Coetsee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT