【问题标题】:How to get the n index numbers before/preceding a specific label?如何在特定标签之前/之前获取 n 个索引号?
【发布时间】:2019-11-04 15:01:56
【问题描述】:

我有一个如下所示的数据集;我的目标是创建一个包含Accepted 之前的三个索引号的列表。

i       Label         value
0       Rejected       12
1       Rejected       10
2       Rejected       22
3       Rejected       32
4       Rejected       25
5       Rejected       15
6       Accepted       42
7       Accepted       52
8       Accepted       17
9       Accepted       8
10      Accepted       10
11      Rejected       21
12      Rejected       32
13      Rejected       12

这个例子的结果应该是:

list = [3,4,5]

编辑: 这种情况在我的数据集中重复了很多次。在某些情况下,Accepted 范围只能是两个样本,如下例所示:

i       Label         value
0       Rejected       12
1       Rejected       10
2       Rejected       22
3       Rejected       32
4       Rejected       25
5       Rejected       15
6       Accepted       42
7       Accepted       52
8       Rejected       17
9       Rejected       8
10      Rejected       10
11      Rejected       21
12      Rejected       32
13      Rejected       12

【问题讨论】:

    标签: python arrays pandas list indexing


    【解决方案1】:

    你可以使用:

    df[df.Label.ne('Accepted')&df.Label.shift(-3).eq('Accepted')].index
    

    Int64Index([3, 4, 5], dtype='int64', name='i')
    

    【讨论】:

    • @anky_91 谢谢。但是,我有一个问题:这段代码可以返回多少个索引?显然,它只能回到很短的时期(少于 6 个指数)。如果我错了,请纠正我。
    • @anky_91 感谢您的回答,但是,这不是一个通用的解决方案,因为 Accepted 范围超过 3 。但是,当您只有一个或两个 Accepted Labels 时,这将不起作用。
    • @AlexDavies 我不明白,你能用更多细节和场景编辑问题吗?谢谢
    • 我编辑了问题,所以对于新示例,代码将无法正常工作。此外,如果我要求超过三个索引,您的代码将无法工作。 (例如:像以前的 2o 个索引)@anky_91
    【解决方案2】:

    你可以使用 .loc:

    index = df.loc[df['Label']=='Accepted', 'Label'].first_valid_index()
    [index - i for i in range(1, 4)]
    >> [5, 4, 3]
    

    【讨论】:

    • 感谢您的回答。但是,这仅在您只有一个案例时才有效。换句话说,如果您希望在数据集中多次执行此类操作,则此代码将不起作用。它仅适用于第一种情况。
    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2020-07-27
    • 2017-11-07
    • 2020-09-11
    • 2013-08-14
    • 2013-05-16
    • 2018-07-30
    相关资源
    最近更新 更多