TransWikia.com

Convert dataset to {row_head, col_head, value} list

Mathematica Asked by Bemtevi77 on June 3, 2021

I have a dataset imported using this method with both row and column head are some numeric values shown below.

sample data

Now I would like to convert the following dataset to a list of {row_head, col_head, value} points for the future plotting.

target list

Currently, I use the following to convert (inspired by this). I wonder is there any other way to do this. Thank you!

x = data[All, List @@@ Normal@Normal@# &];
y = Normal@Normal@x;
z = Function[{t}, Join[{t[[1]]}, #] & /@ t[[2]]] /@ y;
w = ToExpression@Flatten[z,1];

One Answer

Here you'll see two solutions but remember there is always a better way:

MapIndexed

MapIndexed passes positions of elements as arguments. It also works with Dataset and Key:

MapIndexed[{Sequence @@ #2[[All, 1]], #1} &, data, {2}]

The output is a Dataset, so for conversation use:

Normal[MapIndexed[{Sequence @@ #2[[All, 1]], #1} &, data, {2}][Values, Values]]

ReplacePart

With ReplacePart you can use patterns for positions:

ReplacePart[data, {a_, b_} :> {Keys[data][[a]], Keys[data[[b]]][[b]], data[[a, b]]}]

Since a and b are integers like 1,2 instead of Key, Keys[data][[...]] was used. The output is a Dataset, so for conversation use:

Normal[ReplacePart[
   data, {a_, b_} :> {Keys[data][[a]], Keys[data[[b]]][[b]], 
     data[[a, b]]}][Values, Values]]

Note: The speed of MapIndexed is much faster compare to ReplacePart.

Correct answer by Ben Izd on June 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP