簡體   English   中英

計算字典字典中的值數

[英]Counting number of values in dictionaries of dictionary

我目前正在研究用於機器學習的Enron數據集。 但是我陷入了需要為內部字典中的特定鍵找到NaN值的數量的問題。 這是我的字典的示例外觀:

{"Name of person as a key":{"E-Mail":<email of person, if known>, "Salary":<salary off person, if known>}}

嚴格來講,我想找到工資未知的人數,即NaN 我應該如何進行? 提前致謝

您可以這樣做:

    for person in dic:
        salary = dic.get(person).get('salary')
        if not salary:
            print person

這樣您就會得到所有薪水為“無”的人。

假設d是包含相關值的字典的名稱,並且np.nan是通過字符串'NaN'表示的(這似乎是我對Enron數據集的簡要調查):

count = 0
for person in d:
    if d[person].get('Salary') == 'NaN':
        count += 1

您可以這樣做:

count = 0;
for key, value in dict.items():
     if(value['Salary'] is None):
             count+=1

要么

for value in dict.values():
     if(value['Salary'] is None):
             count+=1

或單行:-

sum(1 for value in dict.values() if value['Salary'] is None )

或者,如果需要在其他情況下做一些額外的事情,您可以這樣做:

sum(1 if value['Salary'] is None else 0 for value in dict.values() )

上一行在[表達條件迭代]中對此進行了解釋。

一種更好的方式可以為您提供更多的計數能力:-此表達式返回不可用的工資計數:-

['salary not available' if value['Salary'] is None else ''salary available'' for value in dict.values()].count('salary not available')

這個表達式的薪水回報計數可用:

['salary not available' if value['Salary'] is None else 'salary available' for value in dict.values()].count('salary available')

我是Python的新手,我可以簡單地說這是一種學習自然語言(例如說英語)的偉大語言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM