合并两个 csv(d3)
2013-03-29
2359
我正在使用以下代码加载两个 csv 文件
d3.csv("sqrt100train.csv", function(error, data2) {
d3.csv("sqrt100test.csv", function(error, data) {
sqrt100train 如下所示:
Trees Train
1 0.059286
2 0.057857
3 0.032857
4 0.03619
5 0.022619
而 sqrt100test 如下所示:
Trees Test
1 0.072222
2 0.072778
3 0.044444
4 0.049444
5 0.042778
如何组合这些数组以获得此结果:
Trees Train Test
1 0.059286 0.072222
2 0.057857 0.072778
3 0.032857 0.044444
4 0.036190 0.049444
5 0.022619 0.042778
2个回答
问题:长度或 X 值不同
serie1
X, Y
1, 11
3, 13
5, 15
6, 16
serie2
X, Y
1, 21
2, 22
4, 24
6, 26
7, 27
BothSeries
X, Y1, Y2
1, 11, 21
2, , 22
3, 13,
4, , 24
5, 15,
6, 16, 26
7, , 27
此代码修复了该问题。
var serie1 = [];
var serie2 = [];
var BothSeries = [[null,null,null]];
function merge() {
BothSeries = [];
var i, j, aux;
//copy serie1 a BothSeries
if(serie1.length!=0){
for (var i = 0; i < serie1.length; i++) {
//null represent the serie2 value
BothSeries[i] = [serie1[i][0], serie1[i][1],null];
}
}
//set the value Y of serie2 in the BothSeries when their X are equals.
if(serie2.length!=0){
for (var i = 0; i < serie2.length; i++) {
for (var j = 0; j < BothSeries.length; j++) {
if(BothSeries[j][0] == serie2[i][0]){
BothSeries[j][2] = serie2[i][1];
}
}
}
}
//set the value X and Y of serie2 in the BothSeries when their X aren't equals or doesn't exist.
var cont=0;
if(serie2.length!=0){
for (var i = 0; i < serie2.length; i++) {
for (var j = 0; j < BothSeries.length; j++) {
if(BothSeries[j][0] != serie2[i][0]){
cont++;
}
}
if(cont==BothSeries.length)
{
BothSeries[BothSeries.length] = [serie2[i][0],null,serie2[i][1]];
}
cont=0;
}
}
//order with bubble method by X
if(BothSeries.length!=0){
for(i=0;i<BothSeries.length-1;i++){
for(j=0;j<BothSeries.length-i-1;j++){
if(BothSeries[j+1][0] < BothSeries[j][0])
{
aux=BothSeries[j+1];
BothSeries[j+1]=BothSeries[j];
BothSeries[j]=aux;
}
}
}
}
}
Simon Puente
2014-11-12
如果您想创建新数组:
var newArray = [];
for(var i = 0; i < data.length; i++) {
newArray.push({Trees: data[i].Trees,
Train: data[i].Train,
Test: data2[i].Test});
}
Lars Kotthoff
2013-03-29