# Extracting data from a table under conditions

I have a very large table with two columns. Let's say the name of first column is E and the name of the second is P. How can I get the E values when P = 0.

-

  tbl = RandomInteger[{0, 3}, {10, 2}]
(* {{0, 3}, {0, 0}, {1, 3}, {2, 0}, {2, 0}, {0, 0}, {1, 1}, {2, 2}, {1, 0}, {3, 3}}*)


You have many alternative methods:

  Cases[tbl, {x_, 0} :> x]
(* or *) Cases[tbl, {_, 0}][[All, 1]]
(* or *) DeleteCases[tbl, {_, Except[0]}][[All, 1]]
(* or *) Select[tbl, Last[#] == 0 &][[All, 1]]
(* or *) Pick[tbl[[All, 1]], tbl[[All, 2]], 0]
(* or *) Pick[tbl[[All, 1]], # == 0 & /@ tbl[[All, 2]]]
(* or *) tbl /. {{x_, 0} :> x, {_, _} :> Sequence[]}
(* or *) tbl[[Flatten@Position[tbl[[All, 2]], 0], 1]]
(* or *) tbl[[Flatten@Position[tbl, {_, 0}], 1]]
(* or *) Extract[tbl[[All, 1]], Position[tbl, {_, 0}]]
(* or *) Extract[#[[1]], Position[#[[2]], 0]] &@Transpose@tbl
(* or *) Delete[tbl, Position[tbl, {_, Except[0]}]][[All, 1]]


all give

 {0, 2, 2, 0, 1}

-
Thanks a lot kguler. This is what I want to do. –  TMH Mar 6 '13 at 12:18
@Thakshila, my pleasure. Welcome to Mathematica.SE. –  kglr Mar 6 '13 at 12:25

Something like

Pick @@ Transpose@largetable~Join~{0}


might do it. Unless 0 should be the Real number 0. If you have both, then try

Pick @@ Transpose@largetable~Join~{0 | 0.}


Edit: The above is the same as Apply[Pick, Join[Transpose[largetable], {0 | 0.}]] and has the same effect as

With[{columns = Transpose[largetable]},
Pick[columns[[1]], columns[[2]], 0 | 0.]]


provided largetable is of the form {{E1, P1}, {E2, P2}, ...}.

Edit 2: Example

largetable = Table[{i, RandomInteger[]}, {i, 10}]

Out[1]= {{1, 0}, {2, 0}, {3, 0}, {4, 1}, {5, 0}, {6, 0}, {7, 0}, {8, 1}, {9, 1}, {10, 0}}

With[{columns = Transpose[largetable]},
Pick[columns[[1]], columns[[2]], 0 | 0.]]


Out[2]= {1, 3, 5, 7, 8, 9, 10}

-
Infix has its fans, but will bewilder rookies. –  Yves Klett Mar 6 '13 at 6:16
@YvesKlett Thanks for the feedback. In my own experience, @@ etc. was confusing at the beginning, too. But the advances in Help over the last several versions of Mathematica have improved that considerably. One can select ~, execute the menu command Help > Find Selected Function, and learn about Infix. It seems natural to me to use it with Join, and I guess I forgot it's still somewhat arcane. –  Michael E2 Mar 6 '13 at 11:25
@MichaelE2, Thanks Michael. Could you give an example and show how to write this code. Because, I tried, but there is no result. –  TMH Mar 6 '13 at 12:20
@Thakshila Probably because there were two typos in the With version. Fixed now. This ONE way is more or less equivalent to @kguler's FIFTH way. –  Michael E2 Mar 6 '13 at 13:28
Thanks a lot Michael. –  TMH Mar 6 '13 at 13:56