简体   繁体   中英

Dropping rows based on index and condition

I want to drop certain rows based off of range of rows: I feel like it would look something like the below

df.drop(df.index[[0,1,2,3]])

so that will just drop my first two rows but I would like to drop those rows if and only if that range of rows is blank. so

  Name

  Macy
  June

Jackson

So I would only want to go through the dataframe and drop rows in that range if and only if their is no data so my new dataframe would look like this:

  Name
  Macy
  June
Jackson

You don't need the df.index in the drop statement. However, if you only want to keep the rows where the Name column is filled, you just can use:

> df_filter = df [df.Name != '']

If you really want to locate the rows based on index, you can use

> df_filter = df.drop([0,2])

You can use df.ix to get the excepted items, then drop the None s using dropna() method:

df.ix[indices].dropna()

Demo:

In [48]: df
Out[48]: 
      name
0     None
1     Macy
2     June
3     None
4  Jackson

In [49]: df.ix[[0,1,2,3]].dropna()
Out[49]: 
   name
1  Macy
2  June

Note: As mentioned in comment, since the ix method is deprecated you can use df.loc() instead.

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