I have a very large dataset with about a million entries with up to 75 keys each. Across the whole dataset about half of the keys are blank. In order to reduce filesize, I have used the following code to remove all the blanks keys:
DeleteCases[Normal[data], "", {2}]
I have another much smaller expression with all the keys pointing to blank strings that I can use with KeyUnion
to rebuild the original version if I need to. This works great because it reduces the WL or MX file I am using by about half.
My issue comes when I am trying to use Select
. The ragged dataset works when all entries have the keys present, but if it missing the key, I get an error.
Consider this simplified example:
data = Dataset[{<|"Name" -> "Bob", "Location" -> "USA",
"Job" -> "Police"|>, <|"Name" -> "Jill",
"Location" -> "Canada"|>, <|"Name" -> "Joe", "Location" -> "USA",
"Job" -> "Teacher"|>}]
When all keys are there, I can use Select
as normal:
Select[data, #Location == "USA" &]
But, if one of the entries is missing the key, I get an error:
Select[data, #Job == "Police" &]
There are a few hacky things I can do. I can use KeyUnion to rebuild a full database.
keys = <|"Name" -> "", "Location" -> "", "Job" -> ""|>
Select[KeyUnion[data, keys], #Job == "Police" &]
I can also use KeyExistsQ
to do an initial select and then run from there:
Select[Select[data, KeyExistsQ["Job"]], #Job == "Police" &]
While both of these options yield the results I am looking for, neither are particularly effecient when working with a very large dataset.
I found this question from three years ago that addresses a similar issue with Query
, but since that would have been on V10 and I am in V12, I was hoping something had changed to allow Select
to work with missing keys.
Select[data, Lookup[#, "Job", ""] === "Police" &]
be useful? $\endgroup$KeyExistsQ
. Am I missing something? $\endgroup$Select[data, #Job == "Police"&]
except that it is tolerant of missing keys. $\endgroup$Select
such asContainsAny
,MemberQ
,StringContains
, etc. $\endgroup$