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

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


当前回答

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

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

现在使用索引删除这些行

new_df = df.drop(ind_drop)

其他回答

要删除索引为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. 

我用了一个更简单的方法——只用了两步。

用不需要的行/数据创建一个数据框架。 使用这个不需要的数据帧的索引来删除原始数据帧中的行。

例子: 假设你有一个数据框架df,它有很多列,包括'Age',它是一个整数。现在让我们假设你想删除所有以'Age'为负数的行。

df_age_negative = df[ df['Age'] < 0 ] # Step 1
df = df.drop(df_age_negative.index, axis=0) # Step 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秒,消耗了大量内存。结果的数据帧是相同的。

在对@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是它之前出现的次数。