TransWikia.com

How to select rows based on the entry value of the first column

Mathematica Asked by Anonymouse2020 on January 17, 2021

Data={{0,5678},{0,5654},{1,87675},{2,243},{2,257},{1,9790},{0,7688},{1,97779},{0,6858}}

Given a data set similar to the above, how can I select rows where the first column entry is a number that I specify, and the following row is a row is where the first column entry is another number that I specify, and only alternating first column entries, for instance

Choose 0
Choose 1

I’d like the output to be

{{0,5678},{1,87675},{0,7688},{1,97779}}

Or if I do

Choose 1
Choose 2

I’d like the output to be

{{1,87675},{2,243},}

etc

So far I have

Cases[Data,{n_,_}/;n>=1]

This doesn’t quite do it, but it’s a start. Thanks!

One Answer

SequenceCases

Join @@ SequenceCases[data, {{0, _}, {1, _}}]
{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}
Join @@ SequenceCases[data, {{1, _}, {2, _}}]
{{1, 87675}, {2, 243}}

SequencePosition + Part

Join @@ (data[[#]] & /@ SequencePosition[data[[All, 1]], {0, 1}])
 {{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}
Join @@ (data[[#]] & /@ SequencePosition[data[[All, 1]], {1, 2}])
 {{1, 87675}, {2, 243}}

Split + Select

Join @@ Select[Length @ # >= 2 &] @ Split[data, #[[1]] == 0 && #2[[1]] == 1 &]
{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}
Join @@ Select[Length @ # >= 2 &]@ Split[data, #[[1]] == 1 && #2[[1]] == 2 &]
{{1, 87675}, {2, 243}}

Partition + Select

Join @@ Select[#[[All, 1]] == {0, 1} &] @ Partition[data, 2, 1]
{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}
Join @@ Select[#[[All, 1]] == {1, 2} &] @ Partition[data, 2, 1]
{{1, 87675}, {2, 243}}

BlockMap

BlockMap[If[#[[All, 1]] == {0, 1}, Sequence @@ #, Nothing] &, data, 2, 1]
 {{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}
BlockMap[If[#[[All, 1]] == {1, 2}, Sequence @@ #, Nothing] &, data, 2, 1]
 {{1, 87675}, {2, 243}}

Answered by kglr on January 17, 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