【问题标题】:How to verify if each element in a pandas columns increase strictly by +1 from row to row如何验证熊猫列中的每个元素是否逐行严格增加+1
【发布时间】:2021-12-12 06:51:51
【问题描述】:

假设我有以下 pandas.dataframe:

data

      series    time_idx    value
0        0          0      -0.000000
1        0          1       0.018844
2        0          2       0.028694
3        0          3       0.050784
4        0          4       0.067037
...      ...        ...     ...
3995     9          395     0.973978
3996     9          396     0.944002
3997     9          397     1.001089
3998     9          398     1.132001
3999     9          399     1.169244
4000 rows × 3 columns

我想测试每个系列 (0..9) 的时间索引是否逐行递增 1,如果不是,差异在哪里?

我考虑过按系列和 time_index 对数据帧进行排序,然后与索引 mod 400 进行比较,但这不是一个好的解决方案。有什么建议吗?

谢谢

【问题讨论】:

    标签: python pandas increment


    【解决方案1】:

    以下内容基于我对您的问题的理解。看看这是否回答了你的问题。我必须使用 'True' 而不是 Boolean True,因为数据框会将其转换为数字 1.0。

    df['IncOne'] = (df.series==df.series.shift())
    df['IncOne'] = (
        np.where(df.IncOne, 
            np.where( df.time_idx.eq(df.time_idx.shift()+1), 
                      'True' , df.time_idx-df.time_idx.shift() ),
        ''))
    
    series time_idx value IncOne
    0 0 0 0
    1 0 1 0.018844 True
    2 0 2 0.028694 True
    3 0 3 0.050784 True
    4 0 4 0.067037 True
    5 0 6 0 2.0
    6 0 7 0.018844 True
    7 0 8 0.028694 True
    8 0 9 0.050784 True
    9 0 12 0.067037 3.0
    10 0 13 1 True
    11 9 395 0.973978
    12 9 396 0.944002 True
    13 9 397 1.00109 True
    14 9 398 1.132 True
    15 9 399 1.16924 True

    【讨论】:

      【解决方案2】:

      假设数据框是df,你可以试试这个:

      df["diff"] = df.groupby(by="series")["time_idx"].diff().fillna(1) != 1
      

      它将创建一个带有布尔值的新列"diff"True 值表示当前行中的time_idx 值与其前面的行之间的差值不等于一。只有同系列对应的行之间的差异才能给出True 值。

      【讨论】:

        猜你喜欢
        • 2021-03-22
        • 2020-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 2022-07-11
        • 2020-06-12
        相关资源
        最近更新 更多