Google可视化更改列数据类型 [英] Google Visualization Changing Column Data Type
问题描述
目前我正在从电子表格中提取数据,但其中一些列被列为字符串,一些列为数字。在我将所有数据转换为所有数字的列的数据类型之后,有什么办法吗? 解决方案
您无法更改一旦创建了列的数据类型。解决此问题的方法有两种:向适当类型的DataTable添加新列,填充数据并删除旧列;或者使用DataView将字符串转换为数字。
以下是添加新列的方法:
//假定您要将DataTabledata的第0列转换为键入number
//在所需的索引处插入一个新列;这会将选定索引处或之后的所有列向上颠倒1(因此,列0变为列1,变为2等)。
//将第1列(旧列0)的值复制到第0列,转换为数字
(var i = 0; i< data.getNumberOfRows(); i ++){
var val = data.getValue(i,1); (val!=''&& val!= null){
data.setValue(i,0,new Number(val).valueOf());
//删除第1列(旧列0)
data.removeColumn(1);
以下是使用DataView的示例:
//将第一列转换为键入number
var columns = [{
type:'number',
label:data。 getColumnLabel(0),
calc:function(dt,row){
var val = dt.getValue(row,1);
return(val!=''&& val!= null)?new Number(val).valueOf():null;
}
}];
//填写剩下的列
for(var i = 1; i< data.getNumberOfColumns(); i ++){
columns.push(i);
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
您可以使用DataView而不是DataTable绘制您的可视化文件。
Currently I am pulling data from a spreadsheet, however some of the columns are listed as strings and some are listed as numbers. Is there a way after I pull all the data to convert the data type of the column to all numbers?
You cannot change the data type of a column once it has been created. There are two ways around this problem: either add a new column to the DataTable of the appropriate type, fill it with data, and delete the old column; or use a DataView to convert the strings to numbers on the fly.
Here's how you would add a new column:
// assumes you want to convert column 0 of DataTable "data" to type "number"
// insert a new column at the desired index; this bumps all columns at or after the chosen index up by 1 (so column 0 becomes column 1, 1 becomes 2, etc)
data.insertColumn(0, 'number', data.getColumnLabel(0));
// copy values from column 1 (old column 0) to column 0, converted to numbers
for (var i = 0; i < data.getNumberOfRows(); i++) {
var val = data.getValue(i, 1);
if (val != '' && val != null) {
data.setValue(i, 0, new Number(val).valueOf());
}
}
// remove column 1 (the old column 0)
data.removeColumn(1);
And here's an example of using a DataView:
// convert the first column to type "number"
var columns = [{
type: 'number',
label: data.getColumnLabel(0),
calc: function (dt, row) {
var val = dt.getValue(row, 1);
return (val != '' && val != null) ?new Number(val).valueOf() : null;
}
}];
// fill in the rest of the columns
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columns.push(i);
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
You would draw your visualization(s) using the DataView instead of the DataTable.
这篇关于Google可视化更改列数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!