D3:忽略.csv中的某一行 [英] D3: ignore certain row in .csv

查看:531
本文介绍了D3:忽略.csv中的某一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.csv文件,如下所示:

 开始日期,用户ID,用户名,
date,id,name,
12-12-12,12345,John Doe
01-02-13,67891,Jane Doe
pre>

第一行是第二行上的键的说明。我在.csv文件中加载如下:

  d3.csv(data.csv,function数据){
data.forEach(function(d){
d.date = parseDate(d.date);
d.id = formateID(d.id);
d.name = formatename(d.name);
d.close = + d.close;
});

我想保留第一行(描述)与我的数据模型分开,因为我仍然计划在使用它的路上,但是我不允许修改.csv的格式有一种方法,我只能捕获这些信息:

 日期,ID,名称,
12-12 -12,12345,John Doe
01-02-13,67891,Jane Doe

d3.csv()函数中删除

解决方案

因为你需要干预,你需要加载csv作为纯文本 - 不解析它 - 然后删除第一行,然后将其作为String传递给csv模块进行解析。



要加载,请使用 d3.xhr()
用于解析,请使用 d3.csv.parse()



您最终应该是这样的:

  d3.xhr('data.csv')。get(function(err,response){
var dirtyCSV = response.responseText;
var cleanCSV = dirtyCSV.split('\\\
')。slice(1).join('\\\
');
var parsedCSV = d3.csv.parse(cleanCSV);
})



编辑



这是一个比上面更便宜的转换(这还没有经过测试/调试):

  d3.xhr data.csv')。get(function(err,response){
var dirtyCSV = response.responseText;
var firstEOL = dirtyCSV.indexOf('\\\
');
var parsedCSV = d3.csv.parse(cleanCSV.substring(firstEOL + 1));
})


I have a .csv file that looks like:

The Start Date, The User Id, The User Name,
date, id, name,
12-12-12, 12345, John Doe
01-02-13, 67891, Jane Doe

The first row are descriptions for the keys on the second row. I'm loading in the .csv file as follows:

d3.csv("data.csv", function(error, data) {
  data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.id   = formateID(d.id);
    d.name = formatename(d.name);
    d.close = +d.close;
  });

I want to keep the first row (description) separate from my data model because I still plan on using it down the road, however I'm not allowed to modify the format of the .csv file. Is there a way I can only capture this information:

date, id, name,
12-12-12, 12345, John Doe
01-02-13, 67891, Jane Doe

from the csv?

解决方案

The d3.csv() function does both the loading and the parsing without giving you a chance to intervene. Since you need to intervene, you'll want to load the csv as plain text –– without parsing it –– then remove the first line, and then pass it as a String into the csv module for parsing.

For loading, use d3.xhr() For parsing, use d3.csv.parse().

You should end up with something like this:

d3.xhr('data.csv').get(function (err, response) {
  var dirtyCSV = response.responseText;
  var cleanCSV = dirtyCSV.split('\n').slice(1).join('\n');
  var parsedCSV = d3.csv.parse(cleanCSV);
})

Edit

Here is a less costly transformation than the one above (this has not been tested/debugged):

d3.xhr('data.csv').get(function (err, response) {
  var dirtyCSV = response.responseText;
  var firstEOL = dirtyCSV.indexOf('\n');
  var parsedCSV = d3.csv.parse(cleanCSV.substring(firstEOL+1));
})

这篇关于D3:忽略.csv中的某一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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