我已经为此苦苦挣扎了几天-我读了很多类似的文章,并使用了它们的代码答案。基本上,我试图从此数据框中过滤出(删除)行:
Name: df
OrderQty InvoiceDate
CID
1000363 6 1/20/2020
1002047 1 10/14/2019
1003565 7 10/9/2019
1003680 5 10/2/2019
1010933 1 12/10/2019
[115547 rows x 2 columns]
Type : 'pandas.core.frame.DataFrame'
Index: CID
使用另一个看起来非常相似的DataFrame:
Name: df2
OrderQty InvoiceDate
CID
1000363 6 1/20/2020
1002047 1 10/14/2019
1003565 7 10/9/2019
1003680 5 10/2/2019
1010933 1 12/10/2019
[6387 rows x 2 columns]
Type : 'pandas.core.frame.DataFrame'
Index: CID
列“ CID”上的df2(每个CID一行-这些是我要从df中删除的CID)与df(多行具有相同CID的许多行)之间存在一对多关系
到目前为止,我已经尝试了以下方法来尝试删除df中具有相同CID的CID的行:
new_df = df[df['CID']].isin(df2[df2['CID']])
给出一个KeyError
cond = df['CID'].isin(df2['CID'])
new_df = df.drop(df[cond].index, inplace = True)
给出一个KeyError
new_df = df['CID'].isin(df2).dropna()
给出一个KeyError
new_df = df[~df['CID'].isin(df2)].dropna()
给出一个KeyError
new_df = df.query('CID not in @df2')
没有错误,但不会从df中删除和记录
new_df = df[~df.CID.isin(df2)]
给出AttributeError:'DataFrame'对象没有属性'CID'
我目前还很困-我已经多次关闭/重置我的python应用程序,从我每次阅读的各种帖子中使用了不同的代码段(上),并且没有任何变化。我认为我遇到的问题可能是将“ CID”作为索引或正在处理的一对多关系?
提前致谢!!!
熊猫drop
使用标签,默认情况下,这些标签将成为DataFrame的索引。在您的情况下,CID是索引,因此它应该像
df_new = df.drop(df2.index)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句