# How to select several columns from a dataset

I have a dataset with 20 columns. For a analysis I need all columns except the columns 9 and 11. What I do is:

data[[All, {1,2,3,4,5,6,7,8,  10,   12,13,14,15,16,18,18,19,20}]];


My question: is there a smarter way to do this

• Try something like ds[All, Cases[Range[20], Except[9 | 11]]] Commented Sep 7, 2020 at 12:58
• Part[data, All, Complement[Range[20], {9, 11}]]  Commented Sep 7, 2020 at 14:48

data = ConstantArray[Range[20], 5];
MatrixForm[data]


You can use Delete:

Map[Delete[{{9}, {11}}]] @ data // MatrixForm


Alternatively:

data[[All, DeleteCases[9 | 11] @ Range[20]]]
data[[All, Delete[{{9}, {11}}] @ Range[20]]]
MapAt[Nothing &, data, {All, {9, 11}}]
Module[{d = data}, d[[All, {9, 11}]] = Nothing; d]
Transpose @ ReplacePart[ {{9}, {11}} -> Nothing] @ Transpose @ data
ReplacePart[data, {_, 9 | 11} -> Nothing] (* thanks: WReach *)

• +1 ReplacePart[data, {_, 9 | 11} -> Nothing] would work too. Commented Sep 7, 2020 at 16:15
– kglr
Commented Sep 7, 2020 at 16:30

If you have a Dataset with capital D:

Using Drop:

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" -> {}|>}];

dataset[All, Drop[#, {2}] &]


{2} would be {{9}, {11}} in your case.

• Drop[#, {9, 11}]& would drop columns 9, 10 and 11. Drop works with ranges, not indices. You'd need Delete[#, {{9}, {11}}]& if you want to keep column 10. Commented Sep 7, 2020 at 21:21
• @SjoerdSmit Thanks, good catch! Commented Sep 8, 2020 at 4:35
• Or: dataset[KeyDrop @ "b"]
– eldo
Commented Aug 26, 2023 at 15:35