You need to enable JavaScript to run this app. 如何读取CSV等数据集的纵向列数据并过滤取值唯一的列
优惠活动
大模型
产品
解决方案
定价
更多

如何读取CSV等数据集的纵向列数据并过滤取值唯一的列

实现思路与修改后代码

核心逻辑:要处理列维度的判断,需要先把所有过滤后的有效行暂存,再逐列统计值的唯一性,最后筛选保留列输出。

具体实现步骤

  • 新增集合暂存所有无?的有效行数据,同时确认列总数
  • 逐列遍历,用Set去重统计该列的不同值数量,数量>1的列标记为保留列
  • 遍历所有有效行(包含表头、类型行),仅输出被标记为保留的列内容

注意:原代码用split(" ")分割多空格分隔的内容会生成空字符串,统一替换为split("\\s+")适配多空格分隔场景。

完整代码

public void dataProcessing(){
    File file = new File("insertFilePathHere");
    try {
        Scanner input = new Scanner(file);
        // 读取表头、类型行
        String titles = input.nextLine();
        String[] titleArr = titles.split("\\s+");
        String types = input.nextLine();
        String[] typeArr = types.split("\\s+");
        int columnCount = titleArr.length;

        // 暂存所有有效行
        List<String[]> validRows = new ArrayList<>();
        while (input.hasNext()){
            String line = input.nextLine();
            // 过滤含?的不完整行
            if (line.contains("?")){
                continue;
            }
            String[] row = line.split("\\s+");
            validRows.add(row);
        }

        // 统计需要保留的列索引
        List<Integer> keepColumns = new ArrayList<>();
        for (int col = 0; col < columnCount; col++) {
            Set<String> valueSet = new HashSet<>();
            for (String[] row : validRows) {
                valueSet.add(row[col]);
                // 只要超过1个不同值就可以提前终止当前列的统计,提升效率
                if (valueSet.size() > 1) {
                    break;
                }
            }
            if (valueSet.size() > 1) {
                keepColumns.add(col);
            }
        }

        // 输出过滤后的表头
        for (Integer col : keepColumns) {
            System.out.printf("%10s", titleArr[col]);
        }
        System.out.println();
        // 输出过滤后的类型行
        for (Integer col : keepColumns) {
            System.out.printf("%10s", typeArr[col]);
        }
        System.out.println();
        // 输出过滤后的所有有效行
        for (String[] row : validRows) {
            for (Integer col : keepColumns) {
                System.out.printf("%10s", row[col]);
            }
            System.out.println();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

内容的提问来源于stack exchange,提问作者joJaInDaHouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 01:30:03