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

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

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


当前回答

由于Python中的索引定位是基于0的,因此在索引中对应len(DF)的位置实际上不会有一个元素。你需要last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

然而,只写DF[:-1]要简单得多。

其他回答

由于Python中的索引定位是基于0的,因此在索引中对应len(DF)的位置实际上不会有一个元素。你需要last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

然而,只写DF[:-1]要简单得多。

令人惊讶的是居然没人提这个问题:

# To remove last n rows
df.head(-n)

# To remove first n rows
df.tail(-n)

在1000行的DataFrame上运行速度测试表明,切片和头部/尾部比使用drop快6倍:

>>> %timeit df[:-1]
125 µs ± 132 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.head(-1)
129 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.drop(df.tail(1).index)
751 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

对于具有多索引的更复杂的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。

删除最后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

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

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