Warm tip: This article is reproduced from serverfault.com, please click

python-满足条件的 pandas 在列中删除n行

(python - Pandas once condition is met in column delete n rows)

发布于 2020-11-28 01:04:27

我有一个看起来像的DataFrame df = pd.DataFrame({'col1': [.8,.9,1,1,1,.9,1,.9,.8]})

我的目标是找到“ col1”中的数字1后,删除接下来的五行。

例子

    col1
0   0.8
1   0.9
2   1.0
3   1.0
4   1.0
5   0.9
6   1.0
7   0.9
8   0.8

预期产量

    col1
0   0.8
1   0.9
2   1.0
3   0.8

有任何想法吗?

Questioner
Andrew Horowitz
Viewed
0
sammywemmy 2020-11-28 13:01:25

你可以使用numpy.r_生成整数:

position_of_1 = np.argmax(df.col1.eq(1)) # df.col1.eq(1).idxmax() not fool-proof

integers = np.r_[: position_of_1 + 1, 
                 range(position_of_1 + 6, len(df))
                 ]

df.iloc[integers]


col1
0   0.8
1   0.9
2   1.0
8   0.8

感谢@Ben对np.argmax的建议对于索引不是数字或格式不正确的情况,使用np.argmax会更好/更安全: