簡體   English   中英

如何在數據框中的兩列中交替值?

[英]How to alternate values in two columns in a dataframe?

我正在嘗試創建兩個新列來交替數據幀中的開始和結束:

  1. 對於 1 個開始,最多只有 1 個結束
  2. 最后一個開始可以沒有對應的結束
  3. 在第一次開始之前沒有結束
  4. 連續兩個或多個開始或兩個或多個結束是不可能的

我怎么能在不使用任何循環的情況下做到這一點,所以使用 numpy 或 pandas 函數?

The code to create the dataframe :

df = pd.DataFrame({ 'start':[0,0,1,0,1,0,1,0,0,0,0,1,0,1,0,0,0,1,0],
                    'end':[1,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0]})
The render and the result I want :

   start  end  start wanted  end wanted
0       0    1             0           0
1       0    0             0           0
2       1    0             1           0
3       0    0             0           0
4       1    0             0           0
5       0    0             0           0
6       1    0             0           0
7       0    1             0           1
8       0    0             0           0
9       0    1             0           0
10      0    0             0           0
11      1    0             1           0
12      0    0             0           0
13      1    0             0           0
14      0    0             0           0
15      0    1             0           1
16      0    0             0           0
17      1    0             1           0
18      0    0             0           0

我不知道如何用純 Pandas/numpy 來做到這一點,但這里有一個簡單的 for 循環,可以提供您預期的輸出。 我用 50,000 倍於示例數據大小的 Pandas 數據框對其進行了測試(因此總共大約有 100 萬行),它在大約 1 秒內運行:

import pandas as pd

df = pd.DataFrame({ 'start':[0,0,1,0,1,0,1,0,0,0,0,1,0,1,0,0,0,1,0],
                    'end':[1,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0]})


start = False
start_wanted = []
end_wanted = []
for s, e in zip(df['start'], df['end']):
    if start:
        if e == 1:
            start = False
        start_wanted.append(0)
        end_wanted.append(e)
    else:
        if s == 1:
            start = True
        start_wanted.append(s)
        end_wanted.append(0)


df['start_wanted'] = start_wanted
df['end_wanted'] = end_wanted

print(df)

輸出:

    end  start  start_wanted  end_wanted
0     1      0             0           0
1     0      0             0           0
2     0      1             1           0
3     0      0             0           0
4     0      1             0           0
5     0      0             0           0
6     0      1             0           0
7     1      0             0           1
8     0      0             0           0
9     1      0             0           0
10    0      0             0           0
11    0      1             1           0
12    0      0             0           0
13    0      1             0           0
14    0      0             0           0
15    1      0             0           1
16    0      0             0           0
17    0      1             1           0
18    0      0             0           0

暫無
暫無

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

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