我认为这应该很简单,但我尝试了一些想法,但没有一个奏效:

last_row = len(DF)
DF = DF.drop(DF.index[last_row])  #<-- fail!

我试过使用负号,但这也会导致错误。我肯定还是误解了一些基本的东西。


当前回答

DF。drop((label =None, axis=0, index = last_row)

作为的函数:

DataFrame。drop(label =None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

从行或列中删除指定的标签。

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html

其他回答

DF[:-n]

其中n是最后要删除的行数。

删除最后一行:

DF = DF[:-1]

对于具有多索引的更复杂的dataframe(例如“Stock”和“Date”),并且希望删除每个股票的最后一行,而不仅仅是最后一只股票的最后一行,那么解决方案如下:

# To remove last n rows
df = df.groupby(level='Stock').apply(lambda x: x.head(-1)).reset_index(0, drop=True)

# To remove first n rows
df = df.groupby(level='Stock').apply(lambda x: x.tail(-1)).reset_index(0, drop=True)

由于groupby()向Multi-Index添加了一个额外的级别,我们只需使用reset_index()将其放在末尾。结果df与操作前保持相同类型的Multi-Index。

你知道吗,你只需要在第一行给出-1,像这样

last_row = len(DF) - 1
DF = DF.drop(DF.index[last_row])

使用索引

df.iloc[:-1,:]

这就是iloc存在的原因。你也可以用head或tail。

DF。drop((label =None, axis=0, index = last_row)

作为的函数:

DataFrame。drop(label =None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

从行或列中删除指定的标签。

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html