簡體   English   中英

Pandas DataFrame 基於依賴於具有累積計數規則的其他列的邏輯創建新列

[英]Pandas DataFrame create new columns based on a logic dependent on other columns with cumulative counting rule

我有一個 DataFrame 原來如下:

d1={'on':[0,1,0,1,0,0,0,1,0,0,0],'off':[0,0,0,0,0,0,1,0,1,0,1]}

原來的

我的最終目標是添加一個新列'final',一旦觸發'on'指示器'(忽略任何重復),它將顯示值'1',但如果'final'切換回'0' 'off' 指示器被觸發,並且僅當 'on' 標志被觸發 3 行時。 我確實嘗試提出任何代碼,但根本沒有解決它。

我想要的 output 如下:

期望的

當“on”指示符切換到 1 時,第 1 行中的“final”列首先被觸發。第 3 行中的“on”指示符被忽略,因為它只是一個冗余信號。 第 6 行的“關閉”指示符被觸發,並且“最終”值切換回 0,因為它已經打開超過 3 行,這與第 8 行中觸發“關閉”指示符但“在第 10 行遇到另一個“關閉”指示符之前,無法關閉最終值,因為那是關閉超過 3 行的“最終”值的時間。

謝謝你的幫助。 欣賞。

使用通過yield實現的“狀態機”的一種解決方案:

def state_machine():
    on, off = yield
    cnt, current = 0, on
    while True:
        current = int(on or current)
        cnt += current

        if off and cnt > 3:
            cnt = 0
            current = 0

        on, off = yield current


machine = state_machine()
next(machine)

df = pd.DataFrame(d1)
df['final'] = df.apply(lambda x: machine.send((x['on'], x['off'])), axis=1)

print(df)

印刷:

    on  off  final
0    0    0      0
1    1    0      1
2    0    0      1
3    1    0      1
4    0    0      1
5    0    0      1
6    0    1      0
7    1    0      1
8    0    1      1
9    0    0      1
10   0    1      0
import pandas as pd

d1 = {'on': [0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0], 'off': [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1]}
df = pd.DataFrame(d1)
df['final'], status, hook = 0, 0, 0

for index, row in df.iterrows():
    hook = index if row['on'] else hook
    row['final'] = status = int((row['on'] or status) and (not (row['off'] and index - hook > 2)))
print(df)

Output:

         on  off  final
    0    0    0      0
    1    1    0      1
    2    0    0      1
    3    1    0      1
    4    0    0      1
    5    0    0      1
    6    0    1      0
    7    1    0      1
    8    0    1      1
    9    0    0      1
    10   0    1      0

暫無
暫無

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

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