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

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

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


当前回答

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

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

其他回答

删除最后n行:

df.drop(df.tail(n).index,inplace=True) # drop last n rows

通过同样的方式,可以删除前n行:

df.drop(df.head(n).index,inplace=True) # drop first n rows

使用索引

df.iloc[:-1,:]

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

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

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

Drop返回一个新数组,这就是为什么它在og post中阻塞的原因;我有一个类似的要求,重命名一些列标题,并删除了一些行,因为一个格式不正确的csv文件转换为Dataframe,所以在阅读这篇文章后,我使用:

newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)

它工作得很好,正如你可以看到上面的两条注释掉的行,我尝试了drop.()方法,它工作,但不像使用[n:-n]那样酷和可读,希望能帮助到一些人,谢谢。

我发现的最好的解决方案是不(不一定?)完全复制

df.drop(df.index[-1], inplace=True)

当然,你可以简单地省略inplace=True来创建一个新的数据框架,你也可以通过简单地截取df的切片轻松地删除最后N行。指数(df。index[-N:]删除最后N行)。因此,这种方法不仅简洁,而且非常灵活。