Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

After dropping pandas DataFrame rows, How to still locate a row by the same index?

When you delete a row from a DataFrame, the subsequent rows will shift up with their indexes.. but if you try to locate a row by its index.. you get a different row than expected because the index values have been reset to reflect the new positions of the rows in the DataFrame…
and I want to still be able to locate any of the rows by their original index

for example:
this is before and after I dropped 0 and 2 rows

before:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

after:

enter image description here

and this is what I get when I locate the row with index 1:

enter image description here

how can I still get the row with index 1 ???

>Solution :

Use .loc to index the dataframe by the index name:

df = pd.DataFrame([4,3,2,1])
df.drop([0,2], inplace=True)

# To return a Series
df.loc[1,:]

# Or to return a DataFrame
df.loc[[1],:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading