T. Ato
T. Ato

Reputation: 143

numpy.insert() invalid slice -- Trying to Insert NaN in Numpy Array

I know there are already lots of questions about this, but none of the answers I've seen have solved my problem. I have a pandas DataFrame with 10 columns for data, but on some rows I have just 9 columns-worth of data. For the rows with just 9 datapoints, I need the data to be in the last nine columns. My solution is to insert a NaN value in front of the length-9 arrays so that the data is pushed to the correct columns. But everything I've tried has thrown up errors!

(I'm trying to insert NaN into a numpy array that looks like this: [6070000.0 6639000.0 15004000.0 15944000.0 8888000.0 9896000.0 22502500.0 23577000.0 14835500.0])

My current best guess:

a = np.array(a,dtype=float)
a = np.insert(a,np.nan,0)

**IndexError: invalid slice**

Any ideas about how I can get this doggone NaN into the array?

Upvotes: 0

Views: 586

Answers (1)

Phillip Martin
Phillip Martin

Reputation: 1960

Your code is currently attempting to insert 0 at index np.nan. Switch the args around:

a = np.insert(a, 0, np.nan)

Upvotes: 1

Related Questions