在R中导入CSV文件,移除注释行、单位行并保留唯一列名与数据行
处理TSI Bluesky/AirAssure传感器CSV文件:过滤注释、重复表头和单位行
方法1:使用Python Pandas
适合需要后续数据分析的场景,步骤清晰且灵活:
import pandas as pd # 读取原始CSV,不预设表头,保留所有行 df_raw = pd.read_csv("sensor_data.csv", header=None, skip_blank_lines=False) # 过滤所有以#开头的注释行 df_no_comments = df_raw[~df_raw[0].str.startswith("#", na=False)].reset_index(drop=True) # 定位第一组表头行(替换为你实际的表头第一列名称,比如"PM2.5") header_row_idx = df_no_comments[df_no_comments[0] == "col1"].index[0] # 提取表头内容 column_names = df_no_comments.iloc[header_row_idx].tolist() # 从表头下一行开始提取数据,过滤掉后续重复的表头和单位行 df_clean = df_no_comments.iloc[header_row_idx + 1:] # 替换为实际的表头和单位行标识,比如"col1"是表头,"unit1"是单位行 df_clean = df_clean[~df_clean[0].isin(["col1", "unit1"])].reset_index(drop=True) # 设置列名并转换为数值类型 df_clean.columns = column_names df_clean = df_clean.apply(pd.to_numeric, errors="coerce") # 保存清洗后的文件 df_clean.to_csv("cleaned_sensor_data.csv", index=False)
方法2:使用Awk命令行工具
适合快速批量处理文件,无需编写脚本:
# 处理单个文件 awk ' BEGIN { first_header=1; header_printed=0 } /^#/ { next } # 跳过所有注释行 $1 == "col1" { # 匹配表头行(替换为实际表头第一列) if (first_header) { print $0; header_printed=1; first_header=0 } next # 跳过后续重复表头 } $1 == "unit1" { next } # 跳过单位行(替换为实际单位行第一列) header_printed { print $0 } # 仅在表头打印后输出数据行 ' sensor_data.csv > cleaned_sensor_data.csv # 批量处理所有CSV文件(Linux/macOS) for file in *.csv; do awk ' BEGIN { first_header=1; header_printed=0 } /^#/ { next } $1 == "col1" { if (first_header) { print $0; header_printed=1; first_header=0 } next } $1 == "unit1" { next } header_printed { print $0 } ' "$file" > "cleaned_$file" done
注意事项
- 请根据你实际CSV中的表头名称(比如
PM2.5、Temperature)和单位行内容(比如μg/m³、°C)替换代码中的col1、unit1标识 - 如果单位行的判断不是基于第一列,可调整条件(比如检查整行是否为单位描述)
- 对于多文件批量处理,Python方法可通过循环遍历目录下的CSV文件实现
内容的提问来源于stack exchange,提问作者ay__ya
相关产品推荐
相关产品推荐

