Home > Enterprise >  I work with <query> on DataFrame MutiliIndex (index and columns) My code return the result but
I work with <query> on DataFrame MutiliIndex (index and columns) My code return the result but

Time:02-04

(sory translate remise by discount and prix by price)

MY QUESTION

what compactest code to write to get the result below

enter image description here

My test DataFrame (multiIndex Index Columns)

enter image description here

I Want know

Who producers are selling B grade steel that is priced above 320

First solution

  1. My code

enter image description here

  1. Result

enter image description here

  1. Conclusion

Information : OK but 2 columns are deleted (discount)

Second solution

  1. My code

enter image description here

  1. Result

enter image description here

  1. Conclusion

Information : OK, All columns are present but I lost the multiIndex format

CodePudding user response:

Use Index.get_level_values:

>>> df[(df.index.get_level_values('Métal') == 'Acier')
       & (df.index.get_level_values('Quality') == 'B ')
       & (df['prix'] > 320)]

                           prix  remise_3  remise_4
Producteur Métal Quality                           
Pd1        Acier B        389.0       5.2       8.2

CodePudding user response:

Use only DataFrame.query here:

df = df.query("Métal == 'Acier' & Quality == 'B ' & prix > 320")
print (df)
                           prix  remise_3  remise_4
Producteur Métal Quality                           
Pd1        Acier B        389.0       5.2       8.2
  •  Tags:  
  • Related