簡體   English   中英

我的循環只保存上次迭代的結果

[英]My loop only saves the result of last iteration

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的輸出進行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有列表修真布爾面具的列表,然后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

您可以創建列(系列,列表),然后將其設置為 jezrael 指向的列,或者使用一些初始值創建列,然后在循環中更改它們:

ts["Flagg"] = [0 for _ in range(ts.size)]
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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM