如何在dataframepython中删除后面的行

2024-04-25 19:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮忙。在一个ID的限制中,如何删除第一个满足1的行后面的行?我有一个有两级索引的数据帧。你知道吗

What I have

This is how I want to delete

我试过了

for i in range(1,6):
    for j in range(2013,2016):
        if example_i.loc[i,j]['default']>0:
            example_i.drop(index=[i,j+1])

但这是一个错误:关键错误:2015年

我试过的时候也是个问题

example_i.loc[4,2014]

因为没有这样的争吵。你知道吗


Tags: to数据inidforisexamplehave
1条回答
网友
1楼 · 发布于 2024-04-25 19:56:02

我想不出一种方法能把这个行动干净利落地矢量化。但是扫描数据帧以建立要删除的行的列表是很容易的。所以代码可能是:

电流=0

to_drop = []
for row in example_i.itertuples():
    if cur != row[0][0]:
        cur = row[0][0]
        drop = False
    if drop:
        to_drop.append(row[0])
    if row[1] == 1:
        drop = True

to_drop现在应该是[(1, 2015), (1, 2016), (2, 2016), (4, 2015), (4, 2016), (5, 2015), (5, 2016)]

所以这就足够了:

example_i.drop(to_drop, inplace=True)

正如我们所料:

         default
id time         
1  2013        0
   2014        1
2  2013        0
   2014        0
   2015        1
3  2013        0
   2014        0
   2015        0
   2016        0
4  2013        1
5  2013        0
   2014        1

相关问题 更多 >