在熊猫中找到零元素的列

时间:2020-05-01 13:53:17

标签: python pandas

我想知道如何查找每个包含一些值的所有列?例如零?让我们假设我们有以下字典和相应的数据帧

import  pandas  as pd
import numpy  as np
revenue_per_country ={"Year":[2015,2016,2017,2018,2019,2020],
                      "City":["Paris","Moscow","Rome","New York","California","London"],
                       "Revenue":[30000,40000,50000,5000000,0,100000],
                       "GDP":[3400,4500,5600,67000,30400,0]}
revenue_dataframe =pd.DataFrame(revenue_per_country)
print(revenue_dataframe.head(6))

给定的代码返回以下数据框

  Year        City  Revenue    GDP
0  2015       Paris    30000   3400
1  2016      Moscow    40000   4500
2  2017        Rome    50000   5600
3  2018    New York  5000000  67000
4  2019  California        0  30400
5  2020      London   100000      0

您看到收入和GDP包含一个零元素,在pandas中查找包含某些值的所有列的有效函数是什么?请帮助我

2 个答案:

答案 0 :(得分:3)

使用:

df = revenue_dataframe.loc[:, revenue_dataframe.eq(0).any()]
print (df)
   Revenue    GDP
0    30000   3400
1    40000   4500
2    50000   5600
3  5000000  67000
4        0  30400
5   100000      0

详细信息

首先用DataFrame.eq比较所有值是否相等:

print (revenue_dataframe.eq(0))
    Year   City  Revenue    GDP
0  False  False    False  False
1  False  False    False  False
2  False  False    False  False
3  False  False    False  False
4  False  False     True  False
5  False  False    False   True

然后通过DataFrame.any测试每列至少一个匹配项:

print (revenue_dataframe.eq(0).any())

Year       False
City       False
Revenue     True
GDP         True
dtype: bool

boolean indexing中的最后一个过滤器。但是,由于必须过滤列,因此必须为所有行和列的掩码添加DataFrame.loc和前:

答案 1 :(得分:0)

如果您只想要列名,可以使用:

for column in df.columns:
    if any(df[column]==0) :
        print column