![](/img/trans.png)
[英]In Pandas, how to create a unique ID based on the combination of many columns?
[英]How to create a new column in Pandas DataFrame based on a combination 1 and many columns
我有一個數據集,看起來像這樣:
Cond Column_A Column_B Column_C Cumulative_Count
0 1 -0.60 -0.12 -0.17 1
1 0 0.30 0.70 0.98 0
2 1 -0.45 -0.71 -0.99 2
3 1 0.60 0.12 0.17 1
4 0 0.20 0.80 0.60 0
5 1 0.70 0.14 0.20 1
我想創建一個Cumulative_Count列,該列基於多個條件對事件的發生進行計數,例如:
1)如果Cond = 1並且(Column_A <0.5或Column B> 0.5),則Cumulative_Count = Cumulative_Count + 1
2)如果Cond = 1並且(Column_B <0.5或Column B> 0.5),則Cumulative_Count = Cumulative_Count + 1
3)如果Cond = 1並且(Column_C <0.5或Column C> 0.5),則Cumulative_Count = Cumulative_Count + 1
我想使用NumPy數組來執行它,因為我的數據集非常大。 我嘗試使用下面的代碼,它不會引發錯誤,但是結果不正確。 而且,如果可能的話,我需要對所有列都使用它,因為我有50多個列。
df['Cum_Count']=0
df['Cum_Count']=np.where((df['Cond']>0 & ((df['Column_A']<-0.5) | (df['Column_A']>0.5))), df['Cum_Count']+1, df['Cum_Count'])
一起做
cond1=df.filter(like='Column')
cond2=df.Cond
df['count']=(cond1.gt(0.5)|cond1.lt(-0.5)).__and__(cond2,axis=0).sum(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.