Deleting all keys that have null values
Deleting all keys that have null values
I have a notebook that I am working on that starts with an imported CSV file. Many of the rows have blank data in them. I have used the following command to establish a list of associations:
test = AssociationThread[First[rawdata] -> #] & /@ Rest[rawdata]
The InputForm of the above code produces an end result that is something like this:
InputForm
test = >, <
I want to remove the associations that have blank values so my end result would be more like this:
test2 = <
Is there a simple way to drop all keys across all the entries that have null values? I have looked into KeyDrop / KeyDropFrom but can't figure out a way to drop a key based on its value.
KeyDrop
KeyDropFrom
Based on this thread, I am thinking there may be a way to use Position or PositionIndex.
Position
PositionIndex
Thoughts?
2 Answers
2
Try this:
DeleteCases[test, "", 2]
>
Since this is about a list of associations, the level on which to search the pattern "" is level 2 (only), therefore the 2 as third argument.
""
2
Select:
Select
Select[# != "" &] /@ test
>, <
DeleteMissing:
DeleteMissing
DeleteMissing[test /. "" -> Missing, 2]
"B" -> 6, "C" -> 7
AssociationMap:
AssociationMap
AssociationMap[If[#[[2]] == "", Nothing, #] &] /@ test
<
$begingroup$
For some of my more complicated datasets, this actually provides me with even more functionality. Thanks for the suggestion.
$endgroup$
– kickert
Sep 9 '18 at 17:21
Thanks for contributing an answer to Mathematica Stack Exchange!
But avoid …
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
$begingroup$
Ahh... that makes sense. My earlier attempts didn't take into consideration the level of the key and value.
$endgroup$
– kickert
Sep 9 '18 at 17:20