Make .csv files from arrays in Scala -
i have 2 tuples in scala of following form:
val array1 = (bucket1, seq((datea, amount11), (dateb, amount12), (datec, amount13))) val array2 = (bucket2, seq((datea, amount21), (dateb, amount22), (datec, amount23)))
what quickest way make .csv
file in scala such that:
date*
pivot.bucket*
column name.amount*
fill table.
it needs this:
dates______________bucket1__________bucket2
datea______________amount11________amount21
dateb______________amount12________amount22
datec______________amount13________amount23
you can make shorter chaining operations, :
scala> val array1 = ("bucket1", seq(("datea", "amount11"), ("dateb", "amount12"), ("datec", "amount13"))) array1: (string, seq[(string, string)]) = (bucket1,list((datea,amount11), (dateb,amount12), (datec,amount13))) scala> val array2 = ("bucket2", seq(("datea", "amount21"), ("dateb", "amount22"), ("datec", "amount23"))) array2: (string, seq[(string, string)]) = (bucket2,list((datea,amount21), (dateb,amount22), (datec,amount23))) // single array work scala> val arrays = list(array1, array2) arrays: list[(string, seq[(string, string)])] = list( (bucket1,list((datea,amount11), (dateb,amount12), (datec,amount13))), (bucket2,list((datea,amount21), (dateb,amount22), (datec,amount23))) )
// split between buckets , values scala> val (buckets, values) = arrays.unzip buckets: list[string] = list(bucket1, bucket2) values: list[seq[(string, string)]] = list( list((datea,amount11), (dateb,amount12), (datec,amount13)), list((datea,amount21), (dateb,amount22), (datec,amount23)) ) // format data // note not keep 'datex' order scala> val grouped = values.flatten .groupby(_._1) .map { case (date, list) => date::(list.map(_._2)) } grouped: scala.collection.immutable.iterable[list[string]] = list( list(datec, amount13, amount23), list(dateb, amount12, amount22), list(datea, amount11, amount21) ) // join everything, , add "dates" column in front of buckets scala> val table = ("dates"::buckets)::grouped.tolist table: list[list[string]] = list( list(dates, bucket1, bucket2), list(datec, amount13, amount23), list(dateb, amount12, amount22), list(datea, amount11, amount21) ) // join rows ',' , lines "\n" scala> val string = table.map(_.mkstring(",")).mkstring("\n") string: string = dates,bucket1,bucket2 datec,amount13,amount23 dateb,amount12,amount22 datea,amount11,amount21
Comments
Post a Comment