从dataframe中选择具有非零值的列

时间:2018-04-11 16:51:33

标签: python-2.7 pandas

我有类似以下数据的数据。我只想从数据框中返回包含至少一个非零值的列。因此,在下面的示例中,它将是ALF列。返回非零行似乎并不那么棘手,但选择列和记录会给我带来一些麻烦。

print df

Data:

Type             ADR             ALE     ALF               AME  
Seg0              0.0            0.0     0.0              0.0   
Seg1              0.0            0.0     0.5              0.0 

当我尝试以下链接时:

Pandas: How to select columns with non-zero value in a sparse table

m1 = (df['Type'] == 'Seg0')
m2 = (df[m1] != 0).all()

print (df.loc[m1,m2])

我收到'Type'的重要错误

1 个答案:

答案 0 :(得分:2)

我认为你得到key error,因为第一栏是index

解决方案使用DataFrame.any检查至少一个非零值来屏蔽,然后过滤True s的索引:

m2 = (df != 0).any()
a = m2.index[m2]
print (a)
Index(['ALF'], dtype='object')

或者如果需要list

a = m2.index[m2].tolist()
print (a)
['ALF']

类似的解决方案是过滤列名称:

a = df.columns[m2]

<强>详细

print (m2)
ADR    False
ALE    False
ALF     True
AME    False
dtype: bool