![](/img/trans.png)
[英]In a pandas dataframe, count the number of times a condition occurs in one column?
[英]Count or flag number of times dataframe column reaches a condition
我想要做的是添加一個新列,如果在單獨的列中滿足條件,則基本上“標記” - 如果下一個值<上一個值然后標記它。 為簡單起見,讓 go 為 1(是)和 0(否)。 下面的例子:
DF_原件:
Col1
4
5
3
9
12
11
15
DF_desired:
Col1 Col_flag
4 0
5 0
3 1
9 0
12 0
11 1
15 0
謝謝您的幫助。
您可以使用np.where()
和diff()
來做到這一點:
df = pd.DataFrame({'col1':[4,5,3,9,12,11,15]})
df['Col2'] = np.where(df['col1'].diff() < 0,1,0)
這將是 output:
col1 Col2
0 4 0
1 5 0
2 3 1
3 9 0
4 12 0
5 11 1
6 15 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.