![](/img/trans.png)
[英]Is there a way in Pandas to count (Countifs in excel) in one dataframe and add counts as new column in another dataframe of different length?
[英]Add count column to dataframe that counts when when another row changes
我有一個數據框,其中包含如下列:
x
0 1
1 1
2 0
3 1
4 0
5 0
6 0
7 1
8 1
9 1
我想添加一個每次x
更改時都會計數的列,以便我的最終結果如下所示:
x y
0 1 0
1 1 0
2 0 1
3 1 2
4 0 3
5 0 3
6 0 3
7 1 4
8 1 4
9 1 4
如果沒有循環,我無法找到最快的方法。 如果y
從0或1開始,我也不在乎。我確信我可以使用的是大熊貓的天賦。 你能幫我嗎?
PS。 我需要制作這個y
列的原因是能夠按每個數字對行進行分組,如果有一種方法可以基本上完成同樣的事情而不創建它,那也可以。
diff
你可以應用cumsum
df.x.diff().ne(0).cumsum()-1
Out[132]:
0 0
1 0
2 1
3 2
4 3
5 3
6 3
7 4
8 4
9 4
Name: x, dtype: int32
注意 :這也是object
dtype的推廣,因為我們正在評估相等性。
df.assign(y=np.append(False, df.x.values[1:] != df.x.values[:-1]).cumsum())
x y
0 1 0
1 1 0
2 0 1
3 1 2
4 0 3
5 0 3
6 0 3
7 1 4
8 1 4
9 1 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.