![](/img/trans.png)
[英]remove all rows in pandas dataframe with mixed data types that contain a specific string in multiple columns
[英]How to remove rows where all numerical columns contain zero in Pandas Dataframe with mixed type of columns?
我有以下數據框:
import pandas as pd
df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1],'tag':['apple','orange','grapes','lemon']})
df = df[["tag","a","b"]]
看起來像這樣:
In [37]: df
Out[37]:
tag a b
0 apple 0 0
1 orange 0 1
2 grapes 1 0
3 lemon 1 1
我想做的是刪除數值列為零的行,從而導致:
tag a b
orange 0 1
grapes 1 0
lemon 1 1
我該如何實現?
請注意,實際上,列數可以大於2,並且列名可以更改。 因此,我們需要一個通用的解決方案。
我試過了,但沒有效果:
df[(df.T != 0).any()]
獲取數字列:
numcols = df.dtypes == np.int64
創建索引器
I = np.sum((df.loc[:,numcols]) != 0,axis = 1) != 0
df[I]
tag a b
1 orange 0 1
2 grapes 1 0
3 lemon 1 1
這個答案有一些不同的事情,請讓我知道是否有什么特別令人困惑的地方:
df.loc[~ (df.select_dtypes(include=['number']) == 0).all(axis='columns'), :]
所以:
.all()
方法(默認為行) ~
df.loc[]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.