julia JSON.parse 丢失类型信息 [英] julia JSON.parse losing type information

查看:35
本文介绍了julia JSON.parse 丢失类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 julia,但我遇到了这个问题:

I just started to learn julia but I have this issue:

我正在尝试使用 julia 的 JSON.parse 来解析矩阵(坐标列表),但它正在丢失类型信息.

I am trying to use julia's JSON.parse to parse a matrix (a list of coordinates) but it is losing the type information.

coords = JSON.parse("[[1.0,-2.0],[3.0,4.0],[5.0,-1.2]]")

它返回 Any 类型而不是 Float 类型:

it is returning the Any type instead of the Float type:

3-element Array{Any,1}:
 {1.0,-2.0}
 {3.0,4.0} 
 {5.0,-1.2}

如何获取(或将其转换)为浮点数组?

How do i get (or convert this) to an Array of floats?

编辑.这是更大的问题:

taxi_df = readtable("./test.csv")
coords = [JSON.parse(x) for x in taxi_df[:POLYLINE]]
times = [float(length(x)*15) for x in coords]
df_submission = DataFrame()
df_submission[:TRIP_ID] = taxi_df[:TRIP_ID]
mean_time = mean(times)
df_submission[:TRAVEL_TIME] = [max(x, mean_time) for x in times]
writetable("submission.csv", df_submission)

推荐答案

我认为首先这样做是因为该数据是 JSON 中的列表列表,因此无法转换为矩阵.

I think its doing that in the first place because that data is a list-of-lists in JSON, so it can't convert to a matrix.

你可以做到

float(hcat(coords...))

如果这些是列,或者

float(hcat(coords...))'

如果它们是行.如果此代码的效率至关重要,也可以只预先分配输出矩阵并使用 for 循环,例如

if they are rows. If efficiency is critical for this code, can also just preallocate the output matrix and use a for loop, e.g.

A = zeros(3,2)
for i in 1:3, j in 1:2
  @inbounds A[i,j] = coords[i][j]
end

这篇关于julia JSON.parse 丢失类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆