我想计算从.csv文件导入的15分钟数据的最大值。文件中的每一行都包含来自不同日期("ID"
)的不同来源("Date"
)的15分钟数据,但是不需要其他列("Class", "Sample", "Channel"
)供我分析。
我看过使用d3.group
,但是似乎没有五个键值(每个非数字值一个)是正确的解决方法。
导入数据如下:
[
{
"ID": "10D1012B",
"Class": "R",
"Sample": "135_OLD",
"Channel": "1",
"Date": "1/1/2019",
"00:15": "0.48",
"00:30": "0.6",
"00:45": "0.896",
"01:00": "0.712",
"01:15": "1.12",
...
"23:00": "0.48",
"23:15": "0.6",
"23:30": "0.624",
"23:45": "0.552",
"00:00": "0.704"
},
{
"ID": "10D1040B",
"Class": "R",
"Sample": "135_OLD",
"Channel": "1",
"Date": "1/2/2019",
"00:15": "1.016",
...
"23:30": "0.632",
"23:45": "0.72",
"00:00": "0.776"
}
]
我想计算每一行数据(ID,日期对)的最大值,因此可以使用它来创建图表比例。我不清楚在计算最大值时如何排除非数字列。
答案 0 :(得分:1)
您有两个问题:首先,d3.max
在相同的数组中遍历不同的对象 ...但是,您需要遍历不同的值在同一 object 中。其次,您也不想包含一些数值,例如"Channel"
属性。因此,这并不像在属性中找到所有数值那样简单。
const nonNeededKeys = ["ID", "Class", "Sample", "Channel", "Date"];
...,然后对阵列内每个对象中的所有其他键使用d3.max
:
data.forEach(function(row) {
const keys = d3.keys(row).filter(function(d) {
return nonNeededKeys.indexOf(d) === -1;
});
row.maxValue = d3.max(keys.map(function(d) {
return +row[d]
}))
});
如您所见,在这里,对于每个对象,我正在创建一个名为maxValue
的新属性。
这是演示:
const data = [{
"ID": "10D1012B",
"Class": "R",
"Sample": "135_OLD",
"Channel": "1",
"Date": "1/1/2019",
"00:15": "0.48",
"00:30": "0.6",
"00:45": "0.896",
"01:00": "0.712",
"01:15": "1.12",
"23:00": "0.48",
"23:15": "0.6",
"23:30": "0.624",
"23:45": "0.552",
"00:00": "0.704"
},
{
"ID": "10D1040B",
"Class": "R",
"Sample": "135_OLD",
"Channel": "1",
"Date": "1/2/2019",
"00:15": "1.016",
"23:30": "0.632",
"23:45": "0.72",
"00:00": "0.776"
}
];
const nonNeededKeys = ["ID", "Class", "Sample", "Channel", "Date"];
data.forEach(function(row) {
const keys = d3.keys(row).filter(function(d) {
return nonNeededKeys.indexOf(d) === -1;
});
row.maxValue = d3.max(keys.map(function(d) {
return +row[d]
}))
});
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
此后,很容易计算所有对象的最大值:
const maxValue = d3.max(data, function(d) {
return d.maxValue;
});
正在运行的代码段:
const data = [{
"ID": "10D1012B",
"Class": "R",
"Sample": "135_OLD",
"Channel": "1",
"Date": "1/1/2019",
"00:15": "0.48",
"00:30": "0.6",
"00:45": "0.896",
"01:00": "0.712",
"01:15": "1.12",
"23:00": "0.48",
"23:15": "0.6",
"23:30": "0.624",
"23:45": "0.552",
"00:00": "0.704"
},
{
"ID": "10D1040B",
"Class": "R",
"Sample": "135_OLD",
"Channel": "1",
"Date": "1/2/2019",
"00:15": "1.016",
"23:30": "0.632",
"23:45": "0.72",
"00:00": "0.776"
}
];
const nonNeededKeys = ["ID", "Class", "Sample", "Channel", "Date"];
data.forEach(function(row) {
const keys = d3.keys(row).filter(function(d) {
return nonNeededKeys.indexOf(d) === -1;
});
row.maxValue = d3.max(keys.map(function(d) {
return +row[d]
}))
});
const maxValue = d3.max(data, function(d) {
return d.maxValue
})
console.log(maxValue)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>