2
$\begingroup$

COnsider a list

table = {{x1,y1,z1,t1},{x2,y2,z2,t2},...}

How to remove duplicates having the same values of {y,z} (say, {1,2,3,5},{99,2,3,9})? It is not important for me which exactly row will be remained.

$\endgroup$
5
$\begingroup$

You can use DeleteDuplicatesBy

DeleteDuplicatesBy[#[[{2, 3}]]&] @ table

Example:

table = RandomInteger[3, {7, 4}]

 {{1, 0, 1, 0}, {0, 0, 1, 1}, {0, 1, 0, 0}, {0, 2, 3, 0}, {3, 0, 1, 2}, {2, 3, 3, 0}, {3, 0, 1, 3}}

DeleteDuplicatesBy[#[[{2, 3}]] &] @table

{{1, 0, 1, 0}, {0, 1, 0, 0}, {0, 2, 3, 0}, {2, 3, 3, 0}}

Alternatively, you can use Union:

Union[table, SameTest -> (#[[{2, 3}]] == #2[[{2, 3}]] &)]

{{0, 0, 1, 1}, {0, 1, 0, 0}, {0, 2, 3, 0}, {2, 3, 3, 0}}

Note that DeleteDuplicatesBy keeps the elements that appear early in the original list while Union sorts the list.

$\endgroup$
  • 1
    $\begingroup$ Just to add: for large lists, DeleteDuplicatesBy is also significantly faster than using Union with SameTest since it does not have to run the test on each possible pair. If you want the output sorted, it's probably better to use DeleteDuplicatesBy and then Sort. $\endgroup$ – Sjoerd Smit Jun 25 at 11:19

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.