【问题标题】:Delete rows in Dataframe based on condition in another Dataframe根据另一个数据框中的条件删除数据框中的行
【发布时间】:2019-01-25 16:07:41
【问题描述】:

我熟悉如何根据以下条件删除数据框中的行:

df1 = df1.drop(df1[<some boolean condition>].index)

让 df1 和 df2 是大小相同的 DataFrame。问题是删除 df2 中满足 df1 上述条件的相同索引行。我正在寻找一个优雅的解决方案,而不是保留索引,然后为 df2 再次迭代它们。

例子:

         df1                
    index  value
    1        4
    2        5
    3        6
    4        3
    1        1
    2        5
    1        3
    2        3
    3        2
    4        2
    5        1
    6        7
    7        12

      df2   
 index  value
    1        4
    2        5
    3        7
    4        3
    1        1
    2        109
    1        44
    2        3
    3        2
    4        2
    5        1
    6        7
    7        12

索引不是连续的,所以简单的 df.drop 不起作用。它基于之前创建的组。

【问题讨论】:

  • 定义“相同的行”。如果您的意思是相同的索引,那么只需将df1[&lt;some boolean condition&gt;].index 存储在一个变量中(比如idx)并使用df2 = df2.drop(idx)
  • 是的,我的意思是相同大小的数据帧中的相同索引行
  • 您能否添加一个快速示例来说明您希望它如何工作?就像放置两个 3x3 数据框并告诉我们您希望它如何工作?我想我可以解决它,但我不知道你的问题是什么。

标签: python pandas dataframe


【解决方案1】:

首先,您应该修复数据框中的索引。除非索引是连续的,否则您要执行的操作将不起作用,因为您将通过按索引删除来删除多行。你应该尽量避免many to many relationships in data analytics - they simply cause more problems then they solve)。

试试这样的:

df1.reset_index()
df2.reset_index()
for indexes, row in df1.iterrows():
    if df1.columnname = 2: #imaginary value, place Boolean condition here
       df1.drop(df1.index[[indexes]])
       df2.drop(df2.index[[indexes]])

【讨论】:

  • 我总是可以使用 df=df.groupby('Person').apply(lambda x: x.reset_index(drop=True)).drop('Person', axis=1).reset_index() 假设 Person 是 groupby 变量
  • 上述修复有帮助吗?
猜你喜欢
  • 2018-06-22
  • 1970-01-01
  • 2021-01-07
  • 2019-02-04
  • 2016-11-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2018-06-04
相关资源
最近更新 更多