Python : How to find in set of rows, 一个元素小于1而其他元素大于1?

标签 python pandas

我正在绞尽脑汁地想知道如何才能做这样的事情。

我有一个看起来像这样的数据框...

                A           B           C           D           E
1/2/2012 9:18   0.997558702 1.001294498 1.004264524 1.002337408 1.003628447
1/2/2012 9:19   1.004805553 1.001939237 1.002523232 1.001323543 1.003615329
1/2/2012 9:20   1.001151359 1.001290323 0.997728668 0.999937057 1
1/2/2012 9:21   1.001680821 1.003221649 1.001661232 1.000220313 1.003746398
1/2/2012 9:22   0.998454473 0.998715478 0.998095823 0.996286973 0.996985357
1/2/2012 9:23   0.996461899 0.99903537  1.00055388  0.999778915 0.997408207
1/2/2012 9:24   1.002174781 0.999034438 1.000492065 1.001232033 0.997978923
1/2/2012 9:25   0.999379982 1.00064433  0.998708963 1.000063103 0.999855345

我想找出行所在的位置 sets where one element is > 1 and other is < 1 or reverse <1 或 >1 的顺序无关紧要。尽管比较必须在同一列内连续进行,这一点很重要。我想按数据帧的列计算所有此类出现的次数

所以输出类似

      A B C D E 
index 4 2 5 4 1

我试图思考循环并继续添加,但不知何故认为应该有更好的方法从数据帧中进行选择。

这个问题已得到解答,但正如约翰建议的那样,包括伪代码和列名称。 对于每一行,如果 row < 1 且 row.shift(1) > 1 或 row > 1 且 row.shift(1) < 1 计数

我试图检查的是我是否可以避免以两种方式检查它,因为本质上它在列中以任何一种方式查找 +ve -ve 组合。

P.S>> 我正在检查该数据集的均值回归趋势。

最佳答案

在尝试任何巧妙的方法之前,我发现阐明简单的版本会有所帮助。仅使用 bool 比较、shift,以及我们可以对 bool 列求和来获取 True 的数量,因为 int(True) == 1,我们可以这样做:

>>> (((df < 1) & (df.shift() > 1)) | ((df > 1) & (df.shift() < 1))).sum()
0    4
1    2
2    5
3    4
4    1
dtype: int64

它适用于 bool 框架,看起来像

>>> (df < 1) & (df.shift() > 1)
                   0      1      2      3      4

1/2/2012 9:18  False  False  False  False  False
1/2/2012 9:19  False  False  False  False  False
1/2/2012 9:20  False  False   True   True  False
1/2/2012 9:21  False  False  False  False  False
1/2/2012 9:22   True   True   True   True   True
1/2/2012 9:23  False  False  False  False  False
1/2/2012 9:24  False  False  False  False  False
1/2/2012 9:25   True  False   True  False  False

我认为相对容易阅读。


一个稍微光滑的版本——尽管说实话,可能太光滑了——可能是这样的

>>> s = np.sign(df - 1)
>>> (s == -s.shift()).sum()
0    4
1    2
2    5
3    4
4    1
dtype: int64

但很难看出这是否达到了预期的效果。 (我写的,我只有大约 85% 的信心。)

关于Python : How to find in set of rows, 一个元素小于1而其他元素大于1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499905/

相关文章:

python - 当 'index length mismatch' 时,将索引从 DataFrame 复制到第二帧

Python 和 Beautifulsoup 网页抓取 - 选择具有特定子标签的段落

python - 在 Python 中轻松发出 YAML

python-3.x - pandas SettingWithCopyWarning 仅在函数内部

python - 我怎样才能得到 Pandas 的条件每小时平均值?

python pandas 按组排序

python - 在 gitlab CI 中运行 plotly dash selenium 测试

python - xlsxwriter,openpyxl : 'Workbook' object has no attribute 'write'

python - 如何在 for 循环中堆叠多个 pandas DataFrame

Python DataFrame - 根据同一数据帧的列中的值选择数据帧行