0
$\begingroup$

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];
$\endgroup$
0
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ Thank you very much. Both methods are very nice, particularly the 1st when I tried on a dataset of over 1M pts. $\endgroup$
    – Bemtevi77
    Apr 12 '21 at 5:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.