python - Pandas 中具有 NaN 值的子集列

标签 python pandas

在 SO 上搜索并尝试了几个答案,但它们都是为了返回带有 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

最佳答案

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

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

然后通过isnull查询和 any :

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

最后使用 index 进行 bool 索引:

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

关于python - Pandas 中具有 NaN 值的子集列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43652054/

相关文章:

python & pandas - 如何计算 DataFrame 中列条件下的频率?

python - PyQt4中自定义WM_NAME和WM_CLASS(如xprop所示)

python - Pandas 按行添加另一列

python - 跨多个数据框的 bool 比较

python - 如何将 `style` 与 DataFrame 上的 `to_html` 类结合使用?

python - 如何通过增加单个集合中的文档数量来提高 ArangoDB 2.7 中的检索查询性能

python - django migration 创建只有一个字段的表

python - 缺少可选依赖项 'tables' 。在 Pandas to_hdf

python - 检查 pandas df 的列名是否以 "name"开头,并根据现有空白拆分该列

python - 当 Flask 在 Debug模式下重新启动时 Hook