pythonpandasdataframemachine-learningdata-preprocessing

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:

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],:]