【问题标题】:Subset columns with NaN values in PandasPandas 中具有 NaN 值的子集列
【发布时间】:2017-09-24 21:51:23
【问题描述】:

在这里搜索并尝试了几个答案,但它们都是为了返回带有 NaN 的行。我只想返回具有 NaN 值的列。例如下面的df。如何选择列“A”和“LG”?

df = pd.DataFrame(
        {'H': ['a','b', 'c'],
         'A': [np.nan,'d', 'e'],
         'LG':['AR1', 'RO1', np.nan],
         })

print(df)

     A  H   LG
0  NaN  a  AR1
1    d  b  RO1
2    e  c  NaN

【问题讨论】:

标签: python pandas


【解决方案1】:

我认为您需要先将示例中的字符串 NaN 替换为 np.nan

df = pd.DataFrame(
        {'H': ['a','b', 'c'],
         'A': [np.nan,'d', 'e'],
         'LG':['AR1', 'RO1', np.nan],
         })

然后通过isnullany检查:

mask = df.isnull().any()
print (mask)
A      True
H     False
LG     True
dtype: bool

最后使用index 的布尔索引:

print (mask.index[mask])
Index(['A', 'LG'], dtype='object')

如果需要列添加loc:

print (df.loc[:, mask])
     A   LG
0  NaN  AR1
1    d  RO1
2    e  NaN

【讨论】:

    【解决方案2】:

    这将返回所有包含NaN 的列。

    df = pd.DataFrame(
            {'H': ['a','b', 'c'],
             'A': [np.nan,'d', 'e'],
             'LG':['AR1', 'RO1', np.nan],
             })
    
    x = pd.isnull(df).any()
    
    print(df[x.index[x]])
    
         A   LG
    0  NaN  AR1
    1    d  RO1
    2    e  Na
    

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 2019-06-15
      • 2023-03-21
      • 2014-12-02
      相关资源
      最近更新 更多