gpt4 book ai didi

python - 我的循环只保存最后一次迭代的结果

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:43 25 4
gpt4 key购买 nike

import numpy as np
import pandas as pd

这是我的数据:

ts = pd.DataFrame([0,1,2,3,4,5,6,7,8,9,10,11,12])
ts.columns = ["TS"]
start_df = pd.Series([1,3,6])
end_df = pd.Series([2,7,10])

我创建了以下函数来清理我的循环,并创建了一个 for 循环来遍历 ts 中的每个元素并根据 check_if 的输出进行保存。

def check_if(start, ts, end):
if start <= ts <= end:
return 1
else:
return 0

ts["Flagg"] = np.nan
for ix, hour in enumerate (ts["TS"]):
for jx, end in enumerate(end_df):
ts["Flagg"][ix] = check_if(start_df[jx], hour, end_df[jx])

问题是我生成的 ts["Flagg"] 只保存了最后一次迭代的结果,start_df == 6end_df == 10 。我的逻辑在循环中是完全的吗?

编辑:
预期输出

[0,1,1,1,1,2,2,1,1,1,0,0] 

ts["Flagg"]

最佳答案

使用between对 bool 掩码列表进行列表理解,然后对它进行 sum 计数 True 值(像 1 这样的过程),感谢@RafaelC 的改进:

ts['new'] = np.sum([ts['TS'].between(x, y) for x, y in zip(start_df, end_df)], axis=0)
print (ts)
TS new
0 0 0
1 1 1
2 2 1
3 3 1
4 4 1
5 5 1
6 6 2
7 7 2
8 8 1
9 9 1
10 10 1
11 11 0
12 12 0

详细信息:

print ([ts['TS'].between(x, y) for x, y in zip(start_df, end_df)])

[0 False
1 True
2 True
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 False
11 False
12 False
Name: TS, dtype: bool, 0 False
1 False
2 False
3 True
4 True
5 True
6 True
7 True
8 False
9 False
10 False
11 False
12 False
Name: TS, dtype: bool, 0 False
1 False
2 False
3 False
4 False
5 False
6 True
7 True
8 True
9 True
10 True
11 False
12 False
Name: TS, dtype: bool

关于python - 我的循环只保存最后一次迭代的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53132858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com