Alison S Alison S - 3 months ago 15
Python Question

Trying to drop NaN indexed row in dataframe

I'm using python 2.7.3 and Pandas version 0.12.0.

I want to drop the row with the NaN index so that I only have valid site_id values.

print df.head()
special_name
site_id
NaN Banana
OMG Apple

df.drop(df.index[0])

TypeError: 'NoneType' object is not iterable


If I try dropping a range, like this:

df.drop(df.index[0:1])


I get this error:

AttributeError: 'DataFrame' object has no attribute 'special_name'

Answer

I've found that the easiest way is to reset the index, drop the NaNs, and then reset the index again.

In [26]: dfA.reset_index()
Out[26]: 
  index special_name
0   NaN        Apple
1   OMG       Banana

In [30]: df = dfA.reset_index().dropna().set_index('index')

In [31]: df
Out[31]: 
      special_name
index             
OMG         Banana
Comments