Skip to main content
 首页 » 编程设计

python之如何遍历 df 的每一行/列以查看是否存在 0 或 ' '

2024年11月24日11xing901022

我有一个主 df,我想遍历每一行和每一列,检查 0 和 ''。我需要输出它出现的行。麻烦的是,一个是int,另一个是str。因此,我为所有 int 列和 str 分别创建了子集调用 cols 和 df_string。

我可以同时检查整个 df 的 str 和 int 还是我需要单独执行此操作?

这是我的代码:

cols = ['ID', 'Line Manager Id', 'Project ID'] 
df_strings = ['Email', 'Name', 'Department'] 
i = 0 
k = 0 
for i, j in df.iterrows(): 
    if df[cols[i]][j] == 0: 
        print(i) 
        print('incomplete') 
    if df[df_strings[i]][j] == '': 
        print(i) 
        print('incomplete') 

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

请您参考如下方法:

可以同时使用where,stack之后索引是包含0或空白的列

s=df.eq(0)|df.eq('') 
df.where(df.eq(0)|df.eq('')).stack()