18
$\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$
24
$\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$
  • $\begingroup$ I always want to know how to get 16 votes. :) $\endgroup$ – yode Jul 7 '17 at 15:14
11
$\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$
  • $\begingroup$ (+1) So you now have half of Kuba’s +16 at least... (while he is on 21 already) :) $\endgroup$ – gwr Jan 26 at 9:37
  • $\begingroup$ @gwr Anyway, thanks for your that vote. :) $\endgroup$ – yode Jan 26 at 10:18
6
$\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$

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.