【问题标题】:how to get rows before and after from specific value in column pandas如何从熊猫列中的特定值获取前后行
【发布时间】:2021-07-12 15:29:30
【问题描述】:

我有一个数据框,第一步我将在 A 列中找到值大于或等于 0.9 的行,在第二步中,当 A 的值大于或等于 0.9 时,我将获得前后 4 行的行,(注意:前4行,后4行,还包括值大于或等于0.9的行,所以每次满足条件时得到9行并应用一些函数进行计算)

df=pd.DataFrame({'A':[1,1,1,1,1,1,0.91,2,2,2,2,0.95,2],'flag':[1,1,0,1,1,1,5,1,1,0,1,1,1]})


out_put

df_out=pd.DataFrame({'A':[1,1,1,1,0.91,2,2,2,2],'flag':[0,1,1,1,5,1,1,0,1]})

【问题讨论】:

    标签: python-3.x pandas numpy pandas-groupby


    【解决方案1】:

    首先使用布尔掩码并检查您的第一个条件并使用.index属性获取它的索引:

    df=df[df['A']>=0.9]    #1st condition fullfilled 
    

    如果我们不知道确切的值,那么我们可以检查确切值和稍微更多的值之间的值,并为您的第二个条件获取第一次出现值的索引:

    position=df[df['A'].between(0.9,0.99)].index[0]
    

    最后使用loc[]访问器和reset_index()方法:

    resultdf=df.loc[position-4:position+4,:].reset_index(drop=True)  
    #2nd condition fullfilled
    

    现在,如果您打印 resultdf,您将获得所需的输出:

        A       flag
    0   1.00    0
    1   1.00    1
    2   1.00    1
    3   1.00    1
    4   0.91    5
    5   2.00    1
    6   2.00    1
    7   2.00    0
    8   2.00    1
    

    【讨论】:

    • @Anurag Dabas,这是示例数据,这里我们知道如果我们不知道确切值,实际数据中更大的值是 0.91
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多