简体   繁体   中英

How to drop row in pandas dataframe according to a condition on the index of the row

I have a dataframe called Prod with this shape:

carriers         electricity
techs   
ETH_imp          0.000000e+00
T:Arusha         1.786273e+06
T:Dar_es_Salaam  0.000000e+00
T:Dodoma         3.348339e+08
T:Geita          0.000000e+00
ccgt             3.412390e+08

So my Prod.index results in:

Index(['ETH_imp', 'T:Arusha', 'T:Dar_es_Salaam', 'T:Dodoma', 'T:Geita', 'ccgt'],
      dtype='object', name='techs')

I need to drop the rows, whose indexes contain the string 'T:'

I tried Prod=Prod.drop(Prod['T:' in Prod.index].index) , but apparently the boolean inside square parenthesis, 'T:' in Prod.index only returns one false

You can change logic - get all rows if not index values contains or starting by T:

So filter by boolean indexing with ~ for invert mask with str.contains :

df1 = Prod[~Prod.index.str.contains('T:')]

Or str.startswith :

df1 = Prod[~Prod.index.str.startswith('T:')]

print (df1)
          electricity
carriers             
ETH_imp           0.0
ccgt      341239000.0

You can also use Series.str.match

new_df=Prod[~Prod.index.str.match('T:')]
print(new_df)

          electricity
carriers             
ETH_imp           0.0
ccgt      341239000.0

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