python - 如何使用 pandas 计算 Excel 工作表中 if 语句为 true 的次数?

标签 python pandas pandas-groupby

有一个Excel表格,其中有“差异”一栏,其值可以为负数,也可以为正数。所以,我想找到的是,假设如果负值或正值连续出现6次,则将其计为1,依此类推。 我想要的最终结果

Difference  count
12            
-134
34
234
22
23
43
566          1
-23
-21
-235
-58
-787
-34          2
3

最佳答案

下面的代码可以工作,这里是一个简短的概述:

1) 循环“差异”列。

2) 如果数字为正数,则将 plus_counter 加 1,并将减计数器设置为 0。

3) 如果数字为负数,则 minus_counter 增加 1,并将 plus 计数器设置为 0。

4) 如果这些计数器中任何一个的值等于 6,则将相应行的计数列中的值(我们通过将行存储在 row_counter 中来跟踪行)更改为存储在 answer_counter 中的值。然后,将answer_counter加1并将正负计数器重置为0。

注意,由于 0 既不是正数也不是负数,因此它们会被忽略。

import pandas as pd

diff = [
    12,
    -134,
    34,
    234,
    22,
    23,
    43,
    566,
    -23,
    -21,
    -235,
    -58,
    -787,
    -34,
    3
    ]

df = pd.DataFrame(diff, columns = ['Difference'])
df['count'] = 0

plus_counter = 0
minus_counter = 0
row_counter = 0
answer_counter = 1

for each in df['Difference']:

    if each > 0:
        minus_counter = 0
        plus_counter += 1

        if plus_counter == 6:
            df['count'][row_counter] = answer_counter
            plus_counter = 0
            answer_counter += 1

    elif each < 0:
        plus_counter = 0
        minus_counter += 1

        if minus_counter == 6:
            df['count'][row_counter] = answer_counter
            minus_counter = 0
            answer_counter += 1

    row_counter += 1

关于python - 如何使用 pandas 计算 Excel 工作表中 if 语句为 true 的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913221/

相关文章:

python - 如何有效地向从复杂字典创建的 Pandas DataFrame 添加维度

python - Pandas 计算自值>当前单元格以来的行数

python - Pandas - 合并两个具有不同行数的数据框

python - 需要在 pandas 中使用 Series() 转换的帮助

python - 如何通过比较值范围来合并两个 pandas 数据帧(或传输值)

python - 在分组的 Pandas 数据框中的最大值后删除行

python - 时间表示法标准

Python 2 - 解密 Java 的 PBEWithMD5AndDES

python-3.x - 从 pandas 子组中选择 min

python - pandas:从分组数据框中排序和删除行