首页 > 解决方案 > 提取空值的索引号

问题描述

我试图在列中的值为 null 时获取索引号,这是创建函数以使用 pandas 获取 null 的索引号的最佳方法?

提前谢谢。

标签: pythonpandas

解决方案


如果没有数据框的副本,很难确定这里的问题,但它应该属于以下三个类别之一:

import pandas as pd
import numpy as np

示例数据框:

df = pd.DataFrame({'x': ['1', '2', '3', '', ' ', '   ', '5', np.nan]})

该列具有 NULL 值

print(df.loc[df['x'].isnull()])

"""
     x
7  NaN
"""

该列有一个空字符串

print(df.loc[df['x'] == ''])
"""
  x
3  
"""

该列有一个空字符串或仅包含非零数量的空格。

print(df.loc[df['x'].str.strip() == ''])
"""
     x
3     
4     
5     
"""

推荐阅读