5
$\begingroup$

I have a matrix like this one:

test = {{1, "a"}, {3, "b"}}

and I want to convert it into an association like this Association[ {1} → "a",{3} → "b" ] for a classify method.

I have tried using { Most @ # -> Last @ #} without success. Any idea?

Thank you.

$\endgroup$
5
  • $\begingroup$ Try Association[Most[#] -> Last[#] & /@ test]. $\endgroup$ May 31, 2016 at 17:01
  • 5
    $\begingroup$ AssociationThread @@ Transpose@test $\endgroup$
    – yode
    May 31, 2016 at 17:01
  • 3
    $\begingroup$ KeyMap[List]@ %[yode] $\endgroup$
    – Kuba
    May 31, 2016 at 17:02
  • $\begingroup$ Welcome! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour and check the faqs! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$
    – user9660
    May 31, 2016 at 17:15
  • 1
    $\begingroup$ So combining the answers by Kuba and yode reveals: test // RightComposition[ Transpose, Apply[AssociationThread], KeyMap[List] ] for readability. :) $\endgroup$
    – gwr
    May 31, 2016 at 17:25

2 Answers 2

9
$\begingroup$

Here are a few ways, each returning <| {1} -> "a", {3} -> "b" |>:

Association[{#} -> #2 & @@@ test]

GroupBy[test, Most -> Last, First]

ReplacePart[test, {0 -> Association, {_, 0} -> ({#} -> #2 &)}]

test // Query[Association, Most@# -> Last@# &]

test // Query[GroupBy[Most -> Last], First]
$\endgroup$
7
$\begingroup$

Collecting the comments as an answer for the reader.

This was my first thought:

AssociationThread @@ Transpose @ test

<|1 -> "a", 3 -> "b"|>

But an undocumented but somewhat slower function also came to mind:

GeneralUtilities`AssociatePairs[test]

<|1 -> "a", 3 -> "b"|>

Performance

testlist = RandomInteger[100, {1000000, 2}];
GeneralUtilities`AssociatePairs[testlist]; // AbsoluteTiming
AssociationThread @@ Transpose@testlist; // AbsoluteTiming

{1.0462, Null}

{0.160241, Null}

Lists as keys

If you want to use lists for keys, you can apply the KeyMap to the result as mentioned in gwr's comment and Kuba's. Then you will get

<|{1} -> "a", {3} -> "b"|>

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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