繁体   English   中英

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

[英]delete a part of pd.DataFrame with Python

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

您可以使用df.merge(df1, df2, right_index=True, how='inner')函数对两个DataFrame进行df.merge(df1, df2, right_index=True, how='inner') ,而将索引显示在左侧DataFrame中的行中(我不知道为什么,但这会发生当我使用right_index=True ),然后检索这些行的索引。 (我使用了以下问题的答案: 比较Python Pandas DataFrames以匹配行

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM