簡體   English   中英

如果第一列中的元素等於上一行,則增加第二列的值

[英]increment second columns value if element in the first column equals to previous row

有與此類似的問題,但我真正要問的是有點不同。

我想知道是否有一種方法可以在沒有 for 循環(使用 map 或柱狀計算)的情況下實現以下代碼(如果可能或最快的方式)。

我有一個包含 m 行(>1E7)和 n 列的 DataFrame(df)。 列 j+1 以全 1 或全 0 開始。

for i in range(len(df)):
    if df.iloc[i, j] == df.iloc[i-1, j]: 
        df.iloc[i, j+1] = df.iloc[i-1, j+1]+1

所以示例 output 將如下所示:

    ... j j+1 ...
  0 ... 3  1  ...
  1 ... 4  1  ...
  2 ... 4  2  ...
  3 ... 4  3  ...
  4 ... 6  1  ...
  5 ... 6  2  ...
  6 ... 7  1  ...

肯定有一些問題可以回答這個問題:

s = df.iloc[:,j]
blocks = s.ne(s.shift()).cumsum()
df.iloc[:,j+1]= s.groupby(blocks).cumcount() + 1

Output:

   ...  j  j+1   ...
0  ...  3    1   ...
1  ...  4    1   ...
2  ...  4    2   ...
3  ...  4    3   ...
4  ...  6    1   ...
5  ...  6    2   ...
6  ...  7    1   ...

聽起來這就是你想要的。

df['j+1'] = df.groupby('j').cumcount() + 1

Output:

    j   j+1
0   3   1
1   4   1
2   4   2
3   4   3
4   6   1
5   6   2
6   7   1

暫無
暫無

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

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