【问题标题】:Find the Nth row that matches a condition in pandas在 pandas 中查找匹配条件的第 N 行
【发布时间】:2019-02-02 03:24:33
【问题描述】:

假设我有以下数据框:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  4  8  9
3  0  1  0

如何只删除符合条件的行的第 n 个实例(例如 df['a'] == 4 的第二个实例)?

在这种情况下,结果应该是:

   a  b  c
0  1  2  3
1  4  5  6
3  0  1  0

【问题讨论】:

    标签: python pandas dataframe pattern-matching


    【解决方案1】:

    可以获取表达式(df['a'] == 4)的第n个True值的索引。

    nth = 2
    df.drop(df.index[(df['a'] == 4)][nth-1])
    
       a  b  c
    0  1  2  3
    1  4  5  6
    3  0  1  0
    

    在哪里,

    df['a'] == 4
    
    0    False
    1     True
    2     True
    3    False
    Name: a, dtype: bool
    

    还有,

    df.index[(df['a'] == 4)]
    # Int64Index([1, 2], dtype='int64')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多