2

I am using KNeighborsClassifier to classify some values like this:

arr = classifier_3NN.predict(testData_df)
len(arr)
10960

I want to assign this array to a column in a DataFrame, I have checked & it is the same size:

len(df[df['events']=='NaN']['events'])
10960

When I do the following command the array values are not in the column as expected:

df[df['events']=='NaN']['events'] = arr

Can anyone see what I'm doing wrong?

1 Answer 1

1

I think you need isnull for checking NaN values with ix:

df.ix[df['events'].isnull(), 'events'] = arr

But if need replace NaN values by arr better is use fillna by Series created from arr:

arr = [5,7,9]

df = pd.DataFrame({'events':[np.nan, 1, np.nan]})
print (df)
   events
0     NaN
1     1.0
2     NaN

df['events'] = df['events'].fillna(pd.Series(arr, index=df.index))
print (df)
   events
0     5.0
1     1.0
2     9.0
Sign up to request clarification or add additional context in comments.

1 Comment

So do you need replace NaN values in df['events'] by arr?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.