【问题标题】:Number of features in dictionary字典中的特征数
【发布时间】:2016-06-27 09:55:20
【问题描述】:

我正在从这样的泡菜文件中加载数据集

""" Load the dictionary containing the dataset """
with open("final_project_dataset.pkl", "r") as data_file:
    data_dict = pickle.load(data_file)

它工作正常并正确加载数据。这是一行的示例:

'GLISAN JR BEN F': {'salary': 274975, 'to_messages': 873, 'deferral_payments': 'NaN', 'total_payments': 1272284, 'exercised_stock_options': 384728, 'bonus': 600000, 'restricted_stock': 393818, 'shared_receipt_with_poi': 874, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 778546, 'expenses': 125978, 'loan_advances': 'NaN', 'from_messages': 16, 'other': 200308, 'from_this_person_to_poi': 6, 'poi': True, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 71023, 'email_address': 'ben.glisan@enron.com', 'from_poi_to_this_person': 52}

现在,如何获得特征数量?例如(salary, to_messages, .... , from_poi_to_this_person)

我通过打印整个数据集 (print data_dict) 得到这一行,这是结果之一。我想知道有多少特征是通用的,即在整个数据集中没有在字典中指定一个键。

谢谢

【问题讨论】:

  • 那么,你想获取字典中的项目数'GLISAN JR BEN F'
  • 不。我想知道我的字典中有多少特征
  • @Salma 你说的有多少功能是什么意思,请举例说明。
  • @AbdulFatir 我的意思是,有没有办法在不指定现有键的情况下知道我的字典中有多少功能?就像我有一个数据集,我想知道我有多少列而不查询特定的键。

标签: python python-2.7 dictionary


【解决方案1】:

试试这个。

no_of_features = len(data_dict[data_dict.keys()[0]])  

仅当您在 data_dict 中的所有密钥都具有相同数量的功能时,这才有效。

或者干脆

no_of_features = len(data_dict['GLISAN JR BEN F'])  

【讨论】:

  • 是的,和第一行一模一样!有没有办法在不指定密钥的情况下做到这一点?谢谢
  • @Salma 如果对您有用,请标记为答案。 :)
【解决方案2】:
""" Load the dictionary containing the dataset """
with open("final_project_dataset.pkl", "r") as data_file:
  data_dict = pickle.load(data_file)
  print len(data_dict)

【讨论】:

  • 这将打印我没有的特征数的键或行数。
【解决方案3】:

我认为您想找出行字典中使用的所有唯一字段名称的集合的大小。你可以这样找到:

data_dict = {
    'red':{'alpha':1,'bravo':2,'golf':3,'kilo':4},
    'green':{'bravo':1,'delta':2,'echo':3},
    'blue':{'foxtrot':1,'tango':2}
}   
unique_features = set(
    feature
    for row_dict in data_dict.values()
    for feature in row_dict.keys()
)
print(unique_features)
# {'golf', 'delta', 'foxtrot', 'alpha', 'bravo', 'echo', 'tango', 'kilo'}
print(len(unique_features))
# 8

【讨论】:

    【解决方案4】:

    sum 应用于每个嵌套字典的len

    sum(len(v) for _, v in data_dict.items())
    

    v 表示嵌套的字典对象。

    当您在字典上调用迭代器(或类似的东西)时,自然字典会返回它们的键,因此调用 len 将返回每个嵌套字典中的键数,即。功能数量。

    如果特征可能在嵌套对象中重复,则将它们收集在一个集合中并应用len

    len(set(f for v in data_dict.values() for f in v.keys()))
    

    【讨论】:

    • 谢谢,但这不是我的意思。我通过打印整个数据集(打印 data_dict)得到这一行,这是结果之一。我想知道有多少特征是通用的,即在整个数据集中。
    【解决方案5】:

    这就是答案
    https://discussions.udacity.com/t/lesson-5-number-of-features/44253/4

    在这种情况下,我们在名为 enron_data 的数据库中选择 1 个人 SKILLING JEFFREY K。然后我们打印字典中键的长度。

    print len(enron_data["SKILLING JEFFREY K"].keys())
    

    【讨论】:

      猜你喜欢
      • 2018-05-18
      • 2016-10-11
      • 1970-01-01
      • 2017-12-05
      • 2018-08-19
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多