Jake Eli
Jake Eli

Reputation: 23

How do I modify column headers after importing the CSV?

I am attempting to import a csv file using d3.csv() as follows:

d3.csv("mydata.csv", function(d) { 
console.log(d.columns);
}

This outputs "time", "rate", "id". I would like to change the first and last column header names within my program before joining this data to a topojson file. Is there any way to accomplish this?

Upvotes: 2

Views: 2474

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

That property columns is just a property created by d3.csv in the data array:

const csv = `foo,bar,baz
12,14,13
2,16,4
17,42,10`;

const data = d3.csvParse(csv);

console.log(data.columns);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

You can do whatever you want with it:

const csv = `foo,bar,baz
12,14,13
2,16,4
17,42,10`;

const data = d3.csvParse(csv);

data.columns[0] = "I'm a new value!";

console.log(data.columns);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

You can even get rid of it altogether:

const csv = `foo,bar,baz
12,14,13
2,16,4
17,42,10`;

const data = d3.csvParse(csv);

data.columns.length = 0;

console.log(data.columns);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

The real question here is: why do you want to modify it? That property contains all the headers in your CSV file, as the API explains:

The returned array also exposes a columns property containing the column names in input order.

Therefore, the columns property is very useful to access your data array as it is. That being said, changing that property makes little sense, because you don't have the header names anymore, and things can break further on in your code. So, if you want to change the header name, I believe that changing the CSV file itself is a better option.

Upvotes: 1

Related Questions