I am creating a dictionary from a dataframe. And I have two possibilities:
- all dictionary elements come with the value "nan", like this:
bibliography_dict = {'title': nan, 'year': nan, 'authors': nan, 'pmid': nan, 'is_gwas': nan}
or
- there is at least one element with a value other than "nan", like this ("year" element has value):
bibliography_dict = {'title': nan, 'year': 2022, 'authors': nan, 'pmid': nan, 'is_gwas': nan}
What I want is to check if all elements in this dictionary are "nan" (Null or None) and the value None should be added to an array. Otherwise, if there is at least one element with a value other than "nan", it should add the dictionary.
Here is my code: I'm checking like this:
bibliographies = []
bibliography_empty = {"title": None,
"year": None,
"authors": None,
"pmid": None,
"is_gwas": None
}
if bibliography_dict == bibliography_empty:
print("all elements are empty")
bibliographies.append(None)
else:
bibliographies.append(bibliography_dict)
The values of each element in the dictionary come from a dataframe. Here is the information of that dataframe:
Could you help me?
CodePudding user response:
If all values of bibliography_dict
are False
, this will return True
all(x is None for x in bibliography_dict.values())
Example:
# Returns True
bibliography_dict = {"a": None, "b": None, "c": None}
# Retuens False
bibliography_dict = {"a": None, "b": None, "c": 2022}
Getting an an array of None
a = bibliography_dict.values()
if all(x is None for x in a):
bibliographies = list(a)
# bibliographies will be in the form of [None, None ...]
Edit:
If you are having an issue using None
, replace it with nan
(or the specific contents/object that you are scaning for) in the line below. Like so:
all(x is nan for x in bibliography_dict.values())
Edit 2:
I see you are using Pandas, maybe this is what you are after?
bibliography_dict.isnull().values.any()