21
$\begingroup$

I am constructing a dataset like so:

data = Dataset[AssociationThread[Keys[characterCounts], charFrequencies]]

which gives me a dataset that looks like this:

dataset

This is all fine, but as you can see, the columns have no names, so I cannot query the dataset or do any manipulations on the columns because of this. Any suggestions about how to do this?

$\endgroup$
1

3 Answers 3

28
$\begingroup$
data = N @ Normalize[#, Total] & @ Counts @ Characters @ ExampleData[
  {"Text", "DeclarationOfIndependence"}
];

Dataset @ data

enter image description here

Dataset[KeyValueMap[<|"char" -> #, "freq" -> #2|> &, data]]

enter image description here

$\endgroup$
1
  • $\begingroup$ I always want to know how to get 16 votes. :) $\endgroup$
    – yode
    Jul 7, 2017 at 15:14
21
$\begingroup$

Actully we have a easiest way,suppose you have dataset like

dataset=Dataset[{{"a", 10}, {"b", 11}, {"c", 12}, {"d", 5}, {"e", 99}}]

You can add a column name

dataset[All, <|"char" -> 1, "freq" -> 2|>]

Performance

But if you have a large data set,I have compared FIVE solution here

dataset = Dataset[RandomInteger[100, {200000, 2}]];

AbsoluteTiming[dataset[All, <|"col1" -> 1, "col2" -> 2|>];]
AbsoluteTiming[dataset[Map[AssociationThread[{"col1", "col2"} -> #] &]];]
AbsoluteTiming[dataset[All, Apply[<|"col1" -> #, "col2" -> #2|> &]];]
AbsoluteTiming[dataset[All, Association[Thread[{"col1", "col2"} -> #]] &];]
AbsoluteTiming[dataset[All, AssociationThread[{"col1", "col2"} -> {1, 2}]];]

{2.83872, Null}

{0.968482,Null}

{2.15222, Null}

{1.73927, Null}

{3.03586, Null}

$\endgroup$
2
  • 1
    $\begingroup$ (+1) So you now have half of Kuba’s +16 at least... (while he is on 21 already) :) $\endgroup$
    – gwr
    Jan 26, 2019 at 9:37
  • $\begingroup$ @gwr Anyway, thanks for your that vote. :) $\endgroup$
    – yode
    Jan 26, 2019 at 10:18
8
$\begingroup$

Kuba gave an excellent answer if we can't change the way an original data set is generated. If we can change it, instead of the way it is constructed in the OP, we can do the following:

keys = {"a", "b"};
values = {1, 2};
nameKeys = "keys";
nameValues = "values";
data1 = MapThread[<|nameKeys -> #1, nameValues -> #2|> &, {keys, values}] // Dataset

Just for fun, if we can't change the original data set in the OP and a transformation is needed, we can use the underlying structure and do the low level manipulation:

MapThread[<|nameKeys -> #1, nameValues -> #2|> &, 
          data /. {Association | Rule -> List} // Transpose // Normal] // Dataset
$\endgroup$
1
  • $\begingroup$ Best answer by far $\endgroup$ Sep 15, 2020 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.