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

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


当前回答

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

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

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

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

其他回答

正如Dennis Golomazov的回答所建议的,使用逐行删除。您可以选择保留行。假设您有一个要删除的行索引列表,名为indices_to_drop。您可以将其转换为掩码,操作如下:

mask = np.ones(len(df), bool)
mask[indices_to_drop] = False

你可以直接使用这个索引:

df_new = df.iloc[mask]

这个方法的好处是,掩码可以来自任何来源:它可以是一个包含许多列的条件,也可以是其他条件。

真正好的事情是,你根本不需要原始DataFrame的索引,所以索引是否唯一并不重要。

缺点当然是不能用这种方法进行就地放置。

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

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

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

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

考虑一个示例数据框架

df =     
index    column1
0           00
1           10
2           20
3           30

我们想要删除第2和第3个索引行。

方法1:

df = df.drop(df.index[2,3])
 or 
df.drop(df.index[2,3],inplace=True)
print(df)

df =     
index    column1
0           00
3           30

 #This approach removes the rows as we wanted but the index remains unordered

方法2

df.drop(df.index[2,3],inplace=True,ignore_index=True)
print(df)
df =     
index    column1
0           00
1           30
#This approach removes the rows as we wanted and resets the index. 

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

这对我很有效

# 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

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