7
$\begingroup$

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

$\endgroup$
2
  • 4
    $\begingroup$ Try something like ds[All, Cases[Range[20], Except[9 | 11]]] $\endgroup$
    – Carl Lange
    Commented Sep 7, 2020 at 12:58
  • 3
    $\begingroup$ Part[data, All, Complement[Range[20], {9, 11}]] $\endgroup$
    – cvgmt
    Commented Sep 7, 2020 at 14:48

2 Answers 2

9
$\begingroup$
data = ConstantArray[Range[20], 5];
MatrixForm[data]

enter image description here

You can use Delete:

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

enter image description here

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 *)
$\endgroup$
2
  • 3
    $\begingroup$ +1 ReplacePart[data, {_, 9 | 11} -> Nothing] would work too. $\endgroup$
    – WReach
    Commented Sep 7, 2020 at 16:15
  • $\begingroup$ thank you @WReach. Added your suggestion. $\endgroup$
    – kglr
    Commented Sep 7, 2020 at 16:30
5
$\begingroup$

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}] &]

Output

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

$\endgroup$
3
  • 4
    $\begingroup$ 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. $\endgroup$ Commented Sep 7, 2020 at 21:21
  • $\begingroup$ @SjoerdSmit Thanks, good catch! $\endgroup$
    – C. E.
    Commented Sep 8, 2020 at 4:35
  • $\begingroup$ Or: dataset[KeyDrop @ "b"] $\endgroup$
    – eldo
    Commented Aug 26, 2023 at 15:35

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.