我有一个数据框架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

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


当前回答

如上所述,从布尔值中确定索引。

df[df['column'].isin(values)].index

是否比使用此方法确定索引更占用内存

pd.Index(np.where(df['column'].isin(values))[0])

像这样应用

df.drop(pd.Index(np.where(df['column'].isin(values))[0]), inplace = True)

这种方法在处理大数据帧和有限内存时非常有用。

其他回答

要删除索引为1,2,4的行,您可以使用:

df[~df.index.isin([1, 2, 4])]

波浪符~对方法isin的结果求反。另一种选择是删除索引:

df.loc[df.index.drop([1, 2, 4])]

请看下面的数据框架df

df

   column1  column2  column3
0        1       11       21
1        2       12       22
2        3       13       23
3        4       14       24
4        5       15       25
5        6       16       26
6        7       17       27
7        8       18       28
8        9       19       29
9       10       20       30

删除第1列中所有奇数的行

创建一个列n1中所有元素的列表,并只保留那些偶数元素(您不想删除的元素)

Keep_elements = [x for x in df.]列1如果x%2==0]

所有列n1中值为[2,4,6,8,10]的行将被保留或不被删除。

df.set_index('column1',inplace = True)
df.drop(df.index.difference(keep_elements),axis=0,inplace=True)
df.reset_index(inplace=True)

我们将columnn1作为索引,并删除所有不需要的行。然后我们将索引重置回来。 df

   column1  column2  column3
0        2       12       22
1        4       14       24
2        6       16       26
3        8       18       28
4       10       20       30

如果我想删除一个索引为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]

你也可以传递给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

请注意,当您想要执行下拉行时,使用“inplace”命令可能很重要。

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

因为您最初的问题没有返回任何东西,所以应该使用这个命令。 http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.drop.html