我有一个数据框架df:

>>> df
                  sales  discount  net_sales    cogs
STK_ID RPT_Date                                     
600141 20060331   2.709       NaN      2.709   2.245
       20060630   6.590       NaN      6.590   5.291
       20060930  10.103       NaN     10.103   7.981
       20061231  15.915       NaN     15.915  12.686
       20070331   3.196       NaN      3.196   2.710
       20070630   7.907       NaN      7.907   6.459

然后我想删除具有特定序列号的行,这些序列号在列表中表示,假设这里是[1,2,4],然后左:

                  sales  discount  net_sales    cogs
STK_ID RPT_Date                                     
600141 20060331   2.709       NaN      2.709   2.245
       20061231  15.915       NaN     15.915  12.686
       20070630   7.907       NaN      7.907   6.459

什么函数可以做到这一点?


当前回答

如果我想删除一个索引为x的行,我将执行以下操作:

df = df[df.index != x]

如果我想要删除多个索引(比如这些索引在列表unwanted_indexes中),我会这样做:

desired_indices = [i for i in len(df.index) if i not in unwanted_indices]
desired_df = df.iloc[desired_indices]

其他回答

这里有一个具体的例子,我想展示。假设在某些行中有许多重复的条目。如果您有字符串条目,您可以很容易地使用字符串方法找到要删除的所有索引。

ind_drop = df[df['column_of_strings'].apply(lambda x: x.startswith('Keyword'))].index

现在使用索引删除这些行

new_df = df.drop(ind_drop)

只使用Index参数删除行:-

df.drop(index = 2, inplace = True)

多行:-

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

使用DataFrame。删除并传递一系列索引标签:

In [65]: df
Out[65]: 
       one  two
one      1    4
two      2    3
three    3    2
four     4    1
    
    
In [66]: df.drop(index=[1,3])
Out[66]: 
       one  two
one      1    4
three    3    2

如果DataFrame很大,并且要删除的行数也很大,那么通过索引df.drop(df.index[])简单地删除会花费太多时间。

在我的情况下,我有一个多索引的DataFrame的浮动100M行x 3 cols,我需要从它删除10k行。我发现的最快的方法是,完全违反直觉的,取剩下的行。

设indexes_to_drop为要删除的位置索引数组(问题中的[1,2,4])。

indexes_to_keep = set(range(df.shape[0])) - set(indexes_to_drop)
df_sliced = df.take(list(indexes_to_keep))

在我的例子中,这需要20.5秒,而简单的df。掉落花了5分钟27秒,消耗了大量内存。结果的数据帧是相同的。

你也可以传递给DataFrame。删除标签本身(而不是一系列索引标签):

In[17]: df
Out[17]: 
            a         b         c         d         e
one  0.456558 -2.536432  0.216279 -1.305855 -0.121635
two -1.015127 -0.445133  1.867681  2.179392  0.518801

In[18]: df.drop('one')
Out[18]: 
            a         b         c         d         e
two -1.015127 -0.445133  1.867681  2.179392  0.518801

这相当于:

In[19]: df.drop(df.index[[0]])
Out[19]: 
            a         b         c         d         e
two -1.015127 -0.445133  1.867681  2.179392  0.518801