使用地图创建字典&过滤? [英] Creating dictionary with map & filter?
问题描述
我有以下地图和过滤功能,以便将我们的csv文件数据及其列名作为键。
I have the following map and filter functions in order to get my csv file data with their column names as keys.
d3.csv("Sales Export Friendly 3-19-17.csv", function(data) {
sales = data
.map(sale => [
sale["Unit Booked"],
new Date(sale["Booking Date"]).getMonth() + 1,
new Date(sale["Checkin"]).getMonth() + 1,
(new Date(sale["Checkout"]).valueOf() - new Date(sale["Checkin"]).valueOf())/(24*60*60*1000),
+sale["Total Stay"],
(+sale["Total Stay"]) / ((new Date(sale["Checkout"]).valueOf() - new Date(sale["Checkin"]).valueOf())/(24*60*60*1000)),
])
.filter(([unit, date, checkin, LOS, total, avgNight]) => !isNaN(total));
这适用于大多数用途,但我还没有想出如何保留列名称以在d3多维类型的viz(并行坐标)中将它们引用为轴。我认为它可能与使用有关地图和过滤器?
This works for most purposes but I haven't figured out how to retain the column names to reference them as axes in a d3 multidimensional type of viz (parallel coordinates). I think it may have to do with the use of map and filter?
推荐答案
什么时候你广告CSV文件, d3.csv
创建一个名为 columns
的便捷数组属性。
When you load a CSV file, d3.csv
creates a handy array property called columns
.
根据 API :
返回的数组还公开了一个包含列名的
列
属性输入顺序(与Object.keys相反,其迭代顺序是任意的)。
The returned array also exposes a
columns
property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
因此,因为你的回调参数名为 data
,您只需使用以下命令获取列的名称:
Thus, since your callback parameter is named data
, you can get the columns' names simply using:
data.columns
或者将其分配给变量:
var myColumns = data.columns
这是一个演示版来自此 Bostock的bl.ocks 的真实CSV文件:
Here is a demo with a real CSV file from this Bostock's bl.ocks:
d3.csv("https://gist.githubusercontent.com/mbostock/3887051/raw/805adad40306cedf1a513c252ddd95e7c981885a/data.csv", function(data){
console.log(data.columns);
});
<script src="https://d3js.org/d3.v4.min.js"></script>
PS:这个答案是指D3 v4,它应该是答案的默认版本,除非在问题中另有说明。
PS: this answer refers to D3 v4, which should be the default version for answers, unless stated otherwise in the question.
这篇关于使用地图创建字典&过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!