使用Python删除pd.DataFrame的一部分

时间:2016-03-29 14:33:11

标签: python pandas dataframe

我使用DataFrame.iterrows()迭代DataFrame中的行,如果某行符合某些条件,我会将其存储在其他DataFrame中。有没有办法删除出现在它们中的行,如set.difference(another_set)?

我被要求提供一个代码,所以,因为我不知道我的问题的答案,我解决了我的问题,并创建了另一个DataFrame,我保存好数据而不是有两个DataFrame并对它们有所不同两者。

def test_right_chain(self, temp):
    temp__=pd.DataFrame()
    temp_=pd.DataFrame()
    key=temp["nr right"].iloc[0]
    temp_=temp_.append(temp.iloc[0])
    temp=temp[1:]
    for index, row in temp.iterrows():
        print row
        key_=row['nr right']
        if abs(key_-key)==1:
            pass
        elif len(temp_)>2:
            print row
            temp__.append(temp_)
            temp_=pd.DataFrame()
        else:
            temp_=pd.DataFrame()
        temp_=temp_.append(row)
        key=key_
    return temp__

1 个答案:

答案 0 :(得分:0)

您可以使用df.merge(df1, df2, right_index=True, how='inner')函数执行两个DataFrame的交集,留下由左DataFrame中的行显示的索引(我不知道原因,但是当我使用right_index=True时会发生这种情况)然后检索这些行的索引。 (我使用了这个问题的答案:Compare Python Pandas DataFrames for matching rows

df1 = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD'))

df2 = df1.ix[4:8]
df2.reset_index(drop=True,inplace=True)
df2.loc[-1] = [2, 3, 4, 5]
df2.loc[-2] = [14, 15, 16, 17]
df2.reset_index(drop=True,inplace=True)

df3=pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], right_index=True, how='inner')

现在您需要在两个DataFrame中出现的行索引:

indexes= df3.index.values

然后你只需要从DataFrame中删除这些行:

df1=df1.drop(df1.index[indexes])