查找数据框中满足的条件顺序

时间:2018-02-28 14:01:13

标签: python pandas

说我在pandas.DataFrame

中有一组这样的数据
    A      B      C
1   0.96   1.2    0.75
2   0.94   1.3    0.72
3   0.92   1.15   0.68
4   0.90   1.0    0.73
...

我想弄清楚数据符合条件的顺序。如果我在上面的例子中寻找A减少,B减少和C增加,我会得到ABC,因为A首先满足其条件,B是第二,C是第三。

现在我正在试图解决这个问题,但是有没有更好的方法来利用Pandas的功能呢?

1 个答案:

答案 0 :(得分:0)

这是一种方法。这使得假设与您的问题的上下文相匹配,我们可以描述可能的条件,因为前一个值小于或大于当前值。

代码:

def met_condition_at(test_df, tests):
    # for each column apply the conditional test and then cumsum()
    deltas = [getattr(test_df.diff()[col], test)(0).cumsum() for col, test
              in zip(test_df.columns, tests)]

    # the first time the condition is true, cumsum() == 1
    return (pd.concat(deltas, axis=1) == 1).idxmax()

如何?

  1. 我们采用每列的.diff()
  2. 然后我们应用测试来查看差异何时改变迹象
  3. 然后我们在布尔结果上.cumsum(),找到== 1
  4. 的时间
  5. == 1是第一次改变方向时的索引
  6. 时的索引

    测试代码:

    import pandas as pd
    
    df = pd.read_fwf(StringIO(u"""
           A      B      C
           0.96   1.2    0.75
           0.94   1.3    0.72
           0.92   1.15   0.68
           0.90   1.0    0.73"""), header=1)
    print(df)
    
    tests = ('lt', 'lt', 'gt')
    print(met_condition_at(df, tests))
    
    print(''.join(met_condition_at(df, tests).sort_values().index.values))
    

    结果:

          A     B     C
    0  0.96  1.20  0.75
    1  0.94  1.30  0.72
    2  0.92  1.15  0.68
    3  0.90  1.00  0.73
    
    A    1
    B    2
    C    3
    dtype: int64
    
    ABC
    
相关问题