如何在python中总结float列表?

2024-05-27 11:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从我的数据中总结出一个值列表,并在数据达到使用python设置的条件时对其进行标记,如下表所示。在

enter image description here

示例:我有这个数据,使用累积和,我有这个累计和
但是 如果累计数=>;5,则标签X,它将再次开始计数
如果CumSum<;=-5,则其Y并将再次开始添加
否则,标签A,并将继续计数,直到达到条件集。在

如何使用python编写代码?在

我试过建议的答案,但我想不出来。我希望我已经把问题改清楚了。在

谢谢


Tags: 数据答案代码标记ltgt示例列表
3条回答

函数,该函数将生成一个生成器,该生成器将在每次满足条件时返回x和y标签。在

my_list = [2, 3, -3, -2, 4, -4, -1, -2, -5, -6, 7, 2, 4]

def custom_counter(my_list):
    sum = 0
    for num in my_list:
        sum += num
        if not -5 < sum < 5:
            yield "x" if sum > 0 else "y"
            sum = 0

print(list(custom_counter(my_list)))

输出

^{pr2}$

更新,因为您完全改变了问题的上下文和输出期望值

对你的问题有了好几个答案,然后你改变了问题的范围,要求一些不同的东西。这应该是一个新的问题,但由于你已经更新了你的问题,我已经更新了我的答案,以反映你更新的问题。在

import pandas as pd

def custom_counter(my_list):
    total = 0
    label = "A"
    for num in my_list:
        total += num
        if not -5 < total < 5:
            label = "X" if total > 0 else "Y"
            yield [num, total, label]
            total = 0
            label = "A"
        else:
            yield [num, total, label]

my_list = [3.0, 2.5, -4.1, 1.2, -3.8, 2.9, -1.0, 3.4, 3.6, 2.7]
df = pd.DataFrame(custom_counter(my_list), columns=['Data','CumSum','Label'])
print(df)

输出

   Data  CumSum Label
0   3.0     3.0     A
1   2.5     5.5     X
2  -4.1    -4.1     A
3   1.2    -2.9     A
4  -3.8    -6.7     Y
5   2.9     2.9     A
6  -1.0     1.9     A
7   3.4     5.3     X
8   3.6     3.6     A
9   2.7     6.3     X

这里有一个使用abs和for循环的非常简单的方法:我添加了一些注释来帮助遵循代码

data  = [1.7, -0.2, 1.5, 2.3, 1.8, -4.5, 1.6, -3.9]
s, idx = 0, 0 # s will hold the running sum, idx will hold the starting index for each iteration

for i, num in enumerate(data):
  s += num # adding to the sum
  if abs(s) >= 5: #checking if sum is >= 5 or <= -5
    print((idx, i), s) # prints the range the sum was found and the sum
    s, idx = 0, i + 1 # resets the index and sum

打印:

^{pr2}$

我建议使用列表并按索引访问,而不是使用x和{}。这可以使用上面的方法通过附加到列表而不是打印来完成。在

data  = [1.7, -0.2, 1.5, 2.3, 1.8, -4.5, 1.6, -3.9]
s, sums = 0, []

for num in data:
  s += num
  if abs(s) >= 5:
    sums.append(s)
    s = 0

下面列出一个列表:

[5.3, -5.0]

当然,您可以使用枚举方法在原始代码块中包括索引甚至值,但我假设这正是您要查找的。在

下面是一个使用生成器函数的简单明了的方法:

def binsum(l):
    out = 0
    for i in l:
        out += i
        if abs(out) >= 5:
            yield out
            out = 0

^{pr2}$

快速检查添加每个间隔内的累计和:

[4, 0, 1, 3, 1, 1, 3, 1, 2, 0, 1, 2, 3, 2, 4, 3, 1, 1, 4, 1]
 4, 4, 5, 3, 4, 5, 3, 4, 6, 0, 1, 3, 6, 2, 6, 3, 4, 5, 4, 5

相关问题 更多 >

    热门问题