Chan Austin Chan Austin - 3 months ago 13
Python Question

sort out dataframe where index meet certain conditions

I have a data frame like this:

name pe outstanding totals totalAssets
code
300533 abc 30.04 2500.00 10000.00 82066.80
300532 def 31.27 2100.00 8400.00 77945.25
603986 NiT 23.40 2500.00 10000.00 89517.36
600187 ITG 0.00 145562.42 145562.42 393065.88
000652 IGE 929.15 146567.31 147557.39 2969607.50


I want to sort out those rows whose first 3 chars of index isin(['000','300'])

which the result will be:

name pe outstanding totals totalAssets
code
300533 abc 30.04 2500.00 10000.00 82066.80
300532 def 31.27 2100.00 8400.00 77945.25
000652 IGE 929.15 146567.31 147557.39 2969607.50


thanks.

Answer

You can use str to extract the first 3 characters from index:

df[df.index.str[:3].isin(['300', '000'])]

#       name       pe   outstanding    totals    totalAssets
#  code                 
#300533  abc    30.04       2500.00  10000.00       82066.80
#300532  def    31.27       2100.00   8400.00       77945.25
#000652  IGE   929.15     146567.31 147557.39     2969607.50