如何用Python统计CSV文件中多列同时非空的行数?
解决方案:统计CSV指定多列同时非空的行数
针对你需要统计CSV中指定多列同时包含非空值行数的需求,这里提供几种实用的Python实现方案,同时修正你原有代码中的逻辑问题。
核心思路
- 读取CSV文件,定位需要检查的目标列
- 遍历每一行数据,验证目标列的单元格(去除首尾空格后)是否均不为空字符串
- 统计符合条件的行数,若需要可同时将符合条件的行写入新文件
方案一:按列名指定(推荐,直观不易错)
使用csv.DictReader可以直接通过列名访问单元格,无需手动对应列索引,适合按列名指定的场景:
import csv def count_non_empty_rows(csv_path, target_columns): count = 0 with open(csv_path, 'r', encoding='UTF-8') as f: reader = csv.DictReader(f) # 校验目标列是否存在,避免传入无效列名 for col in target_columns: if col not in reader.fieldnames: raise ValueError(f"列名 '{col}' 不存在于CSV文件中") # 遍历每行,检查所有目标列是否同时非空 for row in reader: all_non_empty = all(row[col].strip() != '' for col in target_columns) if all_non_empty: count += 1 return count # 示例调用 csv_file = r"C:\Users\o\Desktop\1.csv" # 统计gender和name同时非空的行数 print(count_non_empty_rows(csv_file, ['gender', 'name'])) # 输出:6 # 统计gender、name、age同时非空的行数 print(count_non_empty_rows(csv_file, ['gender', 'name', 'age'])) # 输出:4
方案二:按列索引指定
如果你习惯使用列索引(表头后第一列索引为0),可以用csv.reader实现:
import csv def count_non_empty_rows_by_index(csv_path, target_col_indices): count = 0 with open(csv_path, 'r', encoding='UTF-8') as f: reader = csv.reader(f) next(reader) # 跳过表头行 for row in reader: # 检查指定索引的列是否均非空(去除首尾空格) all_non_empty = all(row[idx].strip() != '' for idx in target_col_indices) if all_non_empty: count += 1 return count # 示例调用:gender是第2列(索引1),name是第3列(索引2),age是第4列(索引3) csv_file = r"C:\Users\o\Desktop\1.csv" print(count_non_empty_rows_by_index(csv_file, [1, 2])) # 输出:6 print(count_non_empty_rows_by_index(csv_file, [1, 2, 3])) # 输出:4
方案三:同时统计并筛选写入新文件
如果你需要同时将符合条件的行写入新CSV文件,可以结合统计与写入逻辑:
import csv def filter_and_count_non_empty_rows(input_csv, output_csv, target_columns): count = 0 with open(input_csv, 'r', encoding='UTF-8') as infile, open(output_csv, 'w', newline='', encoding='UTF-8') as outfile: reader = csv.DictReader(infile) writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames) writer.writeheader() # 校验目标列有效性 for col in target_columns: if col not in reader.fieldnames: raise ValueError(f"列名 '{col}' 不存在于CSV文件中") for row in reader: all_non_empty = all(row[col].strip() != '' for col in target_columns) if all_non_empty: writer.writerow(row) count += 1 return count # 示例调用 input_path = r"C:\Users\o\Desktop\1.csv" output_path = r"C:\Users\o\Desktop\2.csv" # 筛选gender和name同时非空的行并统计数量 total = filter_and_count_non_empty_rows(input_path, output_path, ['gender', 'name']) print(f"符合条件的行数:{total}") # 输出:6
对你原有代码的说明
你之前的代码逻辑存在问题:
- 仅针对
row_list[2](name列)做判断,未处理多列同时非空的需求 - 两次重复判断
'' in image_id,逻辑冗余且未实现统计功能 - 直接判断
'' in image_id不够准确,应该用if not image_id.strip()来识别空值(包括仅含空格的情况)
内容的提问来源于stack exchange,提问作者lex9527
相关产品推荐
相关产品推荐

