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

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


当前回答

这对我很有效

# Create a list containing the index numbers you want to remove
index_list = list(range(42766, 42798))
df.drop(df.index[index_list], inplace =True)
df.shape

这将删除所创建范围内的所有索引

其他回答

在对@theodros-zelleke的回答的评论中,@j-jones询问如果索引不是唯一的该怎么办。我不得不处理这种情况。我所做的就是在调用drop()之前重命名索引中的重复项,就像这样:

dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)

其中rename_duplicate()是我定义的函数,它遍历index的元素并重命名重复项。我使用了与pd.read_csv()在列上使用的相同的重命名模式,即“%s。%d" % (name, count),其中name是行名,count是它之前出现的次数。

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

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)

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

这对我很有效

# Create a list containing the index numbers you want to remove
index_list = list(range(42766, 42798))
df.drop(df.index[index_list], inplace =True)
df.shape

这将删除所创建范围内的所有索引

使用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

请看下面的数据框架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