[英]Delete initial rows of a pandas dataframe that satisfy column value condition while keeping the sequence values in a column intact
[英]Count the number of values that satisfy a condition in every column of a Pandas dataframe
我有一個包含幾列數據的 dataframe。 在數據中,-1 相當於缺失數據。 我想計算每列中 -1 值的數量。
我相信我可以在加載數據時將 -1 注冊為 NaN/缺失值,然后我看到一些使用 isna() 並計算 boolean 值的東西。 但是,我想做的事情(對每一列應用條件)似乎是我應該知道如何做的基本事情,所以我想弄清楚如何做到這一點。
這是一個例子。 想象一下,我有以下數據框:
row A B C D E
1 3 5 6 9 -1
2 -1 3 -1 2 0
3 -1 -1 -1 1 -1
我想得到的 output 是:
A B C D E
2 1 2 0 2
我嘗試了以下方法:
df.apply(lambda x: x == -1).count() # value returned was the count of all the rows
(df == -1).count() # also returned a count of all the rows.
我查看了與“countif”相關的幾個問題,但它們似乎都將條件應用於 select 行的一列。 我在上面嘗試的兩項來自與將函數應用於每列和計算與每列中的條件匹配的值相關的問題。
評論中建議的重復項是為整個 dataframe 和每列的不同標准尋找單個值。 我希望將相同的條件應用於每一列並獲得每列的結果,如下面的選定答案所示。
我將不勝感激有關如何進行的任何想法或想法。
使用DataFrame.eq
+ DataFrame.sum
:
#You can omit to_frame and T if you don't want a DataFrame.
df.eq(-1).sum().to_frame().T
#(df==-1).sum() #similar
或者如果是str
:
df.eq('-1').sum().to_frame().T
如果行是一列:
df[df.columns[1:]].eq(-1).sum().to_frame().T
A B C D E
0 2 1 2 0 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.