Drop row in a Pandas Dataframe by using index value and index position

Viewed 18

Unable to drop a specific row based on the index value and its index position. For my system it is crucial to use both. Code below.

Current Dataframe :

TICKER  ORDER ID              BUY DATE
TMC         1                     1
TMC         1                     1
TMC         1                     1
TMC         2                     1
RVPH        1                     1
TSLA       150           09/18/2022, 18:10:13
TMC         1                     1
TMC         1                     1

Willing to drop the row with index value == 'TMC', counting three from bottom of the dataframe. It is for purposes of appending data and making it easier for me to modify and format.

This is what I have tried but gives error: ExcelPD = ExcelPD.drop(ExcelPD.loc['TMC'].iloc[-3])

Error: line 4340, in _drop_axis raise KeyError(f"{labels} not found in axis")

1 Answers

ExcelPD.loc['TMC'] selects the TMC row, you can use boolean indexing

# if `TMC` is in index
ExcelPD = ExcelPD[ExcelPD.index != 'TMC']

# if `TMC` in in column
ExcelPD = ExcelPD[ExcelPD['TICKER'] != 'TMC']
# or
ExcelPD = ExcelPD.query("TICKER != 'TMC'")

Or use dropif TMC is in index

ExcelPD = ExcelPD.drop(index='TMC')
Related