如何添加CSV标头 [英] How to add CSV headers

查看:557
本文介绍了如何添加CSV标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在CSV文件中添加一个新的列和标题,以便进行一些计算:

I need to add a new column and header to the CSV file that I want to do some calculations to:

@csv = CSV.read(filename, headers: true, skip_blanks: true, encoding:'windows-1251:utf-8')    

我想添加一个名为New_header的标题,并逐行执行,其中New_header是第1列+第2列的补充。

I want to an additional header called "New_header" and go row by row where New_header is the addition of column 1 + column 2.

我该如何做?

推荐答案

只需将每一行添加到所需的列中,即可添加为新列:

Simply add the column you want to each line - it will be added as a new column at the end:

@csv.each { |line| line['New_header'] = line[0].to_i + line[1].to_i }

示例:

@csv = CSV.parse("column1,column2,column3\n1,2,three\n2,4,six", headers: true)
@csv.each { |line| line['New_header'] = line[0].to_i + line[1].to_i }

puts @csv.to_csv
# => column1,column2,column3,New_header
#    1,2,three,3
#    2,4,six,6

这篇关于如何添加CSV标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆