Griff Griff - 4 months ago 113
Python Question

Remove rows from Pandas DataFrame based on index condition

I have a dataframe like this:

0 1 2 3 4
19238V105 NaN NaN NaN NaN NaN
91731X102 NaN NaN NaN 2450900.0 996600.0
97X1 NaN NaN NaN NaN NaN


I would like to drop all of the rows where:
len(index) != 9
. So the result would be:

0 1 2 3 4
19238V105 NaN NaN NaN NaN NaN
91731X102 NaN NaN NaN 2450900.0 996600.0


EDIT

I wrote this code:

for index, row in df.iterrows():
if len(index) != 9:
df = df.drop(index)


Is there a better way? Also, I'm not entirely sure why both the
index, row
are required and not just
index
. Thanks

Answer

Try this:

df[df.index.str.len() >= 9]