簡體   English   中英

如何在混合類型的列的Pandas Dataframe中刪除所有數字列都為零的行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM