问题描述
我创建了一个函数,其输入是一个熊猫数据框。
它应该返回具有缺失值的行的行索引。
它适用于所有定义的缺失值,除非单元格完全为空 - 即使我试图在 missing_values 列表中将其指定为 [...,""]
。
def missing_values(x):
df=x
missing_values = ["NaN","NAN","NA","Na","n/a","na","--","-"," ","","None","0","-inf"] #common ways to indicate missingness
observations = df.shape[0] # Gives number of observations (rows)
variables = df.shape[1] # Gives number of variables (columns)
row_index_list = []
#this goes through each observation in the first row
for n in range(0,variables): #this iterates over all variables
column_list = [] #creates a list for each value per variable
for i in range(0,observations): #Now this iterates over every observation per variable
column_list.append(df.iloc[i,n]) #and adds the values to the list
for i in range(0,len(column_list)): #Now for every value
if column_list[i] in missing_values: #it is checked,whether the value is a Missing one
row_index_list.append(column_list.index(column_list[i])) #and if yes,the row index is appended
finished = list(set(row_index_list)) #set is used to make sure the index only appears once if there are multiple occurences in one row and then it is listed
return finished
解决方法
可能存在虚假空格,因此请尝试在此行添加 strip()
:
if column_list[i].strip() in missing_values: #it is checked,whether the value is a Missing one
获取包含 missing_values
的行的索引的更简单方法是使用 isin()
和 any(axis=1)
:
x = x.replace('\s+','',regex=True)
row_index_list = x[x.isin(missing_values).any(axis=1)].index
,
当您使用例如 read_csv 或 read_excel 将文件导入 Pandas 时,丢失的变量(字面上丢失)只能使用 np.nan 或其他类型的空值与 numpy 库指定。
(对不起,我在这里做错了,我在做 np.nan == np.nan 时真的很傻)
您可以先将 np.nan 值替换为:
df = df.replace(np.nan,'NaN')
那么你的函数就可以捕获它。
另一种方法是在 pandas 中使用 isna(),
df.isna()
这将返回相同的数据帧,但单元格包含布尔值,对于每个 np.nan 单元格为 True
如果您执行df.isna().any()
,
对于包含空值的任何列,这将返回一个具有 True 值的系列。
如果要检索ID,只需将参数axis = 1 添加到any()
:
df.isna().any(axis = 1)
这将返回一个系列,显示具有 np.nan 值的所有行。
现在您有了指示哪一行包含空值的布尔值。如果将这些布尔值添加到列表中并将其应用于 DF.index,这将删除包含 null 的行的索引值。
booleanlist = df.isna().any(axis =1).tolist()
null_row_id = df.index[booleanlist]