为什么不能按索引号行pd.drop()

时间:2018-11-14 09:47:06

标签: python

Wave    4003.767578 4003.1308590000003  4002.4941409999997  4001.857422 4001.219727 4000.5830079999996  3999.945313 3999.3085939999996  3998.670898 3998.033203 ... 113.323242  112.00585900000002  110.6875    109.36914099999998  108.049805  106.731445  105.41210900000002  104.092773  102.77246099999999  y
P+1 -32.110054  -20.772640  -12.855230  -8.463967   -0.821934   0.032814    -1.098199   0.016086    0.010318    -2.938682   ... -3.681485   -4.898650   -7.486461   -8.193399   -8.814915   -10.837570  -12.422396  -14.679218  -15.527417  0.0
P+2 -5.736303   -5.030378   -0.018224   -3.026827   0.025469    0.050761    0.027413    0.026207    0.044137    0.011986    ... -3.504273   -1.774416   -0.106922   -0.935158   -0.128912   -1.153341   -1.237674   -2.365705   -1.386401   0.0
P+3 -5.481629   -0.013840   0.048731    -0.007416   0.050425    0.196820    0.034959    0.157383    0.136245    0.044136    ... -0.076982   -0.089720   0.097743    -0.117528   -0.126414   -0.140218   -0.155385   -0.171771   -0.183943   0.0
P+4 -0.033687   0.037497    0.099730    0.065606    0.172090    0.211174    0.185221    0.181935    0.190258    0.090686    ... 0.107342    0.111296    0.102923    0.085651    0.073617    0.064088    0.045348    0.021398    0.000000    0.0
P+5 0.000000    0.048679    0.101316    0.125399    0.180421    0.227582    0.208315    0.201352    0.211689    0.175192    ... 0.131808    0.114767    0.114276    0.100220    0.080086    0.065543    0.051642    0.026925    0.000000    0.0

这是我的数据框,我可以按df.drop(['p+1'])行 虽然无法删除索引号,但我尝试使用p1.drop([0:2])p1.drop(p1[0:2])p1.drop(df.index[0:2])并获得

KeyError: 'labels [4003.767578 4003.1308590000003] not contained in axis'

1 个答案:

答案 0 :(得分:0)

您需要获取要删除的行的索引值...

> import pandas as pd
> import numpy as np

> df = pd.DataFrame(np.arange(12).reshape(3,4),
                  columns=['A', 'B', 'C', 'D'],
                  index=['first', 'second', 'third'])
> df
        A  B   C   D
first   0  1   2   3
second  4  5   6   7
third   8  9  10  11
# Drop first row
> df.drop(df.index[[0]])

        A  B   C   D
second  4  5   6   7
third   8  9  10  11

# Drop first and third rows
> df.drop(df.index[[0, 2]])

        A  B  C  D
second  4  5  6  7

之所以有效,是因为df.index[[]]返回行号的索引...

> df.index[[0,2]]

Index(['first', 'third'], dtype='object')

如果要使用范围,则可以使用np.arange() ...

> df.index[[np.arange(0,2)]]
Index(['first', 'second'], dtype='object')

> df.drop(df.index[[np.arange(0,2)]])

       A  B   C   D
third  8  9  10  11