5
$\begingroup$

I want to pick values of varying columns from a dataset, eg. from the Dataset in the documentation

dataset = Dataset[{
   <|"a" -> 1, "b" -> "x", "c" -> {1}|>,
   <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
   <|"a" -> 3, "b" -> "z", "c" -> {3}|>,
   <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,
   <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,
   <|"a" -> 6, "b" -> "z", "c" -> {}|>}]

then

attribute = "b"

I'm now searching something like

dataset[Select[b=="x"]], resp dataset[Select[#b=="x"&]]

This is clearly not working but I think is good enough to show what I am searching for

$\endgroup$
0

1 Answer 1

6
$\begingroup$

Following @Syed, maybe something like this

{attr, val} = {"b", "x"};
Select[dataset, #[attr] == val &]

enter image description here

Also due to @Syed, there is this one

Query[Select[#[attr] == val &]]@dataset

And, we can't leave out

Cases[dataset, _[___, Rule[attr, val], ___]]  (* eyesore *)

Cases[dataset, KeyValuePattern[attr -> val]]  (* legible *)
$\endgroup$
4
  • $\begingroup$ Learned something new here. Could you please refer me to a doc page where I can find more about the #[ ] syntax. Or could you perhaps elaborate how to combine slots with string patterns? $\endgroup$
    – Syed
    Commented Dec 20, 2021 at 8:49
  • $\begingroup$ @Syed I wanted to add this answer as a comment to your answer, but I thought it was too long. I happened to find the #["name"] form of Slot in the Details section of the docs for Slot. Your answer also showed how to use Query. Please, undelete your answer so it can be accepted as the better, more complete one and feel free to add the #["name"] form to your answer. You led me to it. $\endgroup$
    – LouisB
    Commented Dec 20, 2021 at 9:26
  • $\begingroup$ Thanks for the link and for the offer. Very kind of you. I think you can add the Query variant to your answer with proper syntax. I enjoyed experimenting for 20 minutes, and exploring with FullForm etc. before giving up. $\endgroup$
    – Syed
    Commented Dec 20, 2021 at 9:37
  • 1
    $\begingroup$ Thanks for this hint, I was not so lucky to find the "Slot-Trick". BTW a lot of this Dataset operations are not really self explanatory .... $\endgroup$
    – mgamer
    Commented Dec 20, 2021 at 19:32

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.