我有一个看起来像的DataFramedf = pd.DataFrame({'col1': [.8,.9,1,1,1,.9,.7,.9,1,1,.8,.8,.9]})
col1
0 0.8
1 0.9
2 1.0
3 1.0
4 1.0
5 0.9
6 0.7
7 0.9
8 1.0
9 1.0
10 0.8
11 0.8
12 0.9
一旦1位于col1
中,我希望代码删除下面的三个数字。它应该去掉这三个,然后看看下面是否有1。输出应该看起来像。。。
col1
0 0.8
1 0.9
2 1.0
6 0.7
7 0.9
8 1.0
12 0.9
我之前问了一个问题,答案是。
integers = np.r_[: df.twofour.eq(1).idxmax() + 1,
range(df.twofour.eq(1).idxmax() + 30, len(df))
]
df = df.iloc[integers]
这段代码可以删除1的第一个意图,我能帮助扩展所有未删除的1吗?有更优雅的方法吗?
您只需对数据帧进行迭代,即可删除所有索引:
index_to_delete = []
for row in df.itertuples():
idx = row[0]
value = row.col1
if value == 1 and idx not in index_to_delete:
index_to_delete += [idx+1, idx+2, idx+3]
df = df.loc[~df.index.isin(index_to_delete)]
print(df)
输出:
col1
0 0.8
1 0.9
2 1.0
6 0.7
7 0.9
8 1.0
12 0.9