说我在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的功能呢?
答案 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()
.diff()
.cumsum()
,找到== 1
== 1
是第一次改变方向时的索引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