![](/img/trans.png)
[英]Count rows across columns in a dataframe if they are greater than another value
[英]Pandas Count values across rows that are greater than another value in a different column
我有一個這樣的熊貓數據框:
X a b c
1 1 0 2
5 4 7 3
6 7 8 9
我想打印一列“ count”,該列輸出的值的數量大於第一列中的值(在我的情況下為“ x”)。 輸出應如下所示:
X a b c Count
1 1 0 2 2
5 4 7 3 1
6 7 8 9 3
我想避免使用“ lambda函數 ”或“ for ”循環或任何種類的循環技術,因為我的數據幀有很多行。 我嘗試過類似的方法,但是我無法獲得想要的東西。
df['count']=df [ df.iloc [:,1:] > df.iloc [:,0] ].count(axis=1)
我也試過
numpy.where()
也沒有任何運氣。 因此,任何幫助將不勝感激。 我也將nan作為數據框的一部分。 所以我想在計算值時忽略它。
謝謝您的幫助!
您可以將ge
(> =)與sum
df.iloc[:,1:].ge(df.iloc[:,0],axis = 0).sum(axis = 1)
Out[784]:
0 2
1 1
2 3
dtype: int64
分配回去之后
df['Count']=df.iloc[:,1:].ge(df.iloc [:,0],axis=0).sum(axis=1)
df
Out[786]:
X a b c Count
0 1 1 0 2 2
1 5 4 7 3 1
2 6 7 8 9 3
df['count']=(df.iloc[:,2:5].le(df.iloc[:,0],axis=0).sum(axis=1) + df.iloc[:,2:5].ge(df.iloc[:,1],axis=0).sum(axis=1))
萬一任何人需要這樣的解決方案,您只需將從'.le'和'.ge'獲得的輸出添加到一行即可。 感謝@Wen回答我的問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.