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

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

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


当前回答

stats = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv")

统计数据输出:

       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

只需使用skipfooter=1

Skipfooter: int,默认为0 文件底部要跳过的行数

stats_2 = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv", skipfooter=1, engine='python')

stats_2的输出

       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

其他回答

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

由于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]要简单得多。

删除最后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[:-n]

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

删除最后一行:

DF = DF[:-1]

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]那样酷和可读,希望能帮助到一些人,谢谢。