简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM