C++ 读取 CSV 文件并计算列数据标准差和均值

本文将提供 C++ 代码示例,展示如何读取 CSV 文件的某一列,并计算该列数据的标准差和均值,最后将结果写入对应列的末尾。

代码示例

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cmath>

using namespace std;

vector<vector<string> > readCSV(string filename) {
    vector<vector<string> > data;
    ifstream file(filename);
    string line;
    while (getline(file, line)) {
        vector<string> row;
        stringstream ss(line);
        string cell;
        while (getline(ss, cell, ',')) {
            row.push_back(cell);
        }
        data.push_back(row);
    }
    file.close();
    return data;
}

void writeCSV(string filename, const vector<vector<string> >& data) {
    ofstream file(filename);
    for (const auto& row : data) {
        for (const auto& cell : row) {
            file << cell << ',';
        }
        file << endl;
    }
    file.close();
}

int main() {
    string filename = 'data.csv';
    vector<vector<string> > data = readCSV(filename);

    // get the column to calculate
    int col = 2;
    vector<double> nums;
    for (const auto& row : data) {
        nums.push_back(stod(row[col]));
    }

    // calculate the mean and standard deviation
    double mean = accumulate(nums.begin(), nums.end(), 0.0) / nums.size();
    double sq_sum = inner_product(nums.begin(), nums.end(), nums.begin(), 0.0);
    double stdev = sqrt(sq_sum / nums.size() - mean * mean);

    // append the mean and standard deviation to the end of the column
    for (auto& row : data) {
        row[col] += ',' + to_string(mean) + ',' + to_string(stdev);
    }

    writeCSV(filename, data);

    return 0;
}

代码解析

  • 该程序使用了 STL 中的许多算法,例如 accumulateinner_product 来计算均值和标准差,readCSV 函数用于读取 csv 文件,writeCSV 函数用于将数据写入 csv 文件。
  • 这个程序假设 csv 文件中的第三列包含要计算的数据,可以通过修改 col 变量来指定要计算的列。

总结

本文提供了一个 C++ 代码示例,用于读取 CSV 文件的某一列,计算该列数据的标准差和均值,并将结果写入对应列的末尾。代码利用 STL 算法库,实现了高效的数据处理。您可以根据自己的需求修改代码,以满足不同的数据处理任务。

C++ 读取 CSV 文件并计算列数据标准差和均值

原文地址: https://www.cveoy.top/t/topic/niBO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录