【问题标题】:How should I selec which rows I erase in Pandas DataFrame with a two conditions?我应该如何在两个条件下选择我在 Pandas DataFrame 中删除的行?
【发布时间】:2021-08-29 05:52:12
【问题描述】:

我需要为这样的 DataFrame 删除一些行:

import pandas as pd
import numpy as np

input_ = pd.DataFrame()
input_ ['ID'] = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
input_ ['ST'] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
input_ ['V'] = [NaN, NaN, 1, 1, NaN, 1, Nan, 1, NaN, NaN, NaN, NaN]\

并以这样的 DataFrame 结束:

output_ ['ID'] = [ 2, 3, 4, 2, 3, 4, 2, 3, 4]
output_ ['ST'] = [ 1, 1, 1, 2, 2, 2, 3, 3, 3]
output_ ['V'] = [NaN, 1, 1, 1, Nan, 1, NaN, NaN, NaN]

在哪里,我删除了 ID == 1 的行,因为这些行有列 V == float(NaN) [np.isnan(V)] em> 表示 ST 列中的 ALL 值。在这两个条件下,我应该如何选择在 Pandas DataFrame 中删除哪些行?

【问题讨论】:

  • 按照上面链接上的方法,您可以尝试以下方法:input_.drop(input_[(input_['ID']==1) & (input_['V'].isna())].index)
  • @RishabhKumar 你似乎误解了这个问题。 OP 想要删除 ID=1,因为所有带有 ID 的 V 都是 nan。
  • @QuangHoang 好的,它给出了相同的输出,所以没有仔细阅读问题
  • 我有点困惑,因为他说“有这两个条件”,而不同的数据集可能不会在 1 或 2 个条件下得到相同的结果。

标签: python pandas dataframe conditional-statements


【解决方案1】:

使用groupby().transform('any')检查该组是否包含一些notna:

valids = input_.V.notna().groupby(input_.ID).transform('any')

output = input_[valids]

输出:

    ID  ST    V
1    2   1  NaN
2    3   1  1.0
3    4   1  1.0
5    2   2  1.0
6    3   2  NaN
7    4   2  1.0
9    2   3  NaN
10   3   3  NaN
11   4   3  NaN

【讨论】:

    【解决方案2】:

    试试这个:

    input_ = input_[(input_['ID']!=1) & input_['V'].notnull()]
    

    我不确定我是否完全理解您的问题以及您是否想按 1 过滤,或者您是否只是为了摆脱 NaN 值。如果您不想按 ID==1 实际过滤,只需执行以下操作:

    input_ = input_[input_['V'].notnull()]
    

    两者的输出:

       ID  ST    V
    2   3   1  1.0
    3   4   1  1.0
    5   2   2  1.0
    7   4   2  1.0
    

    【讨论】:

      【解决方案3】:
      input_ = pd.DataFrame()
      
      input_ ['ID'] = [1,     2, 3, 4,   1, 2,   3, 4,   1,   2,   3,   4]
      
      input_ ['ST'] = [1,     1, 1, 1,   2, 2,   2, 2,   3,   3,   3,   3]
      
      input_ ['V']  = ['NaN', 'NaN', 1, 1, 'NaN', 1,'Nan', 1, 'NaN', 'NaN', 'NaN', 'NaN']
      
      input_1 = pd.DataFrame(input_)
      
      print(input_1)
      
      input_1.drop(0, inplace = True)
      input_1.drop(4, inplace = True)
      input_1.drop(8, inplace = True)
      
      print(input_1)
      

      【讨论】:

        猜你喜欢
        • 2018-01-17
        • 2022-06-21
        • 1970-01-01
        • 2020-12-22
        • 2015-10-15
        • 2023-02-21
        • 2018-01-11
        • 2022-06-15
        • 2014-09-19
        相关资源
        最近更新 更多