rajsx
rajsx

Reputation: 61

Pandas dataframe with nan in Index

How can I get/select nan in Index of a Dataframe. I have made a MultiIndex dataframe with 4 levels in which 1st level has some nan values which i want in another dataframe

i tried many methods of getting null values but none of those seems to work with index as null heres an example Fruit and color are my index and i want to get those rows with nan values

               Count    Price
Fruit   Color       
Apple   Red     3       $1.29
nan     Green   9       $0.99
Pear    Red     25      $2.59
nan     Green   26      $2.79
Lime    Green   99      $0.39

Upvotes: 2

Views: 679

Answers (1)

jezrael
jezrael

Reputation: 863741

Test first level of MultiIndex extracted by Index.get_level_values with Index.isna and filter by boolean indexing:

df2 = df[df.index.get_level_values(0).isna()]
print (df2)
             Count  Price
Fruit Color              
NaN   Green      9  $0.99
      Green     26  $2.79

Or get MultiIndex.codes and compare by -1:

df2 = df[df.index.codes[0] == -1]
print (df2)
             Count  Price
Fruit Color              
NaN   Green      9  $0.99
      Green     26  $2.79

Upvotes: 6

Related Questions