【问题标题】:Pandas Check for mulitple minimum consequtive criterias熊猫检查多个最小连续标准
【发布时间】:2017-03-15 17:37:45
【问题描述】:

我有一个场景,我想检查一列 (Col1) 中连续 pandas 数据帧行是否满足最低标准 (0.6),当起始值至少为 (0.7) 时,它也符合标准即:

Col1
0.3
0.5
0.55
0.8 = true
0.65 = true
0.9 = true
0.61 = true
0.3
0.6
0.67
0.74 = true
0.63 = true
0.61 = true

换句话说,如果该值至少为 0.7,或者如果该值至少为 0.6 并且之前的值至少为 0.6 且连续序列中的第一个值至少为 0.7,则检查将是 True .

它将运行一个非常大的数据集,因此需要高效。我在想shift() 的东西会起作用...但不能完全正确。

【问题讨论】:

    标签: python pandas dataframe criteria minimum


    【解决方案1】:

    您可以使用Series.where() 来构造逻辑系列。

    步骤

    • 使用nan 值初始化系列;
    • 为所有大于 0.7 的值分配 True
    • 为小于 0.6 的所有值分配 False
    • 前向填充值介于 0.6~0.7 之间,因为它取决于之前的值
    • 在系列开头填充可能的缺失值
    • 将数据类型转换为布尔值(可选)

    所以:

    import pandas as pd
    import numpy as np
    df['check'] = np.nan
    df['check'] = (df['check'].where(df.Col1 < 0.7, True)
                              .where(df.Col1 > 0.6, False)
                              .ffill().fillna(False)
                              .astype(bool))
    

    【讨论】:

    • 非常聪明!谢谢!
    • 如何在不创建名为“检查”的新列的情况下将此检查逻辑用作 col1 的选择标准? IE。 df.col1.loc(...符合您的检查标准...)。如果可能的话我想使用 .loc ()
    • 您可以使用df.Col1[df.check] 进行子集化,然后删除检查列。如果你真的因为某些原因不想创建新列,s = pd.Series([np.nan] * df.shape[0], index = df.index); df.Col1.loc[s.where(df.Col1 &lt; 0.7, True).where(df.Col1 &gt; 0.6, False).ffill().fillna(False).astype(bool)]
    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 2020-12-01
    • 2022-11-11
    • 2020-10-09
    • 2022-10-14
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多