【问题标题】:Pythonic way to convert a dictionary to a numpy array将字典转换为 numpy 数组的 Pythonic 方法
【发布时间】:2014-07-03 05:43:50
【问题描述】:

这更多是关于编程风格的问题。 我为诸如“温度:51-62”、“高度:1000-1500”等字段的网页报废了结果保存在字典中

{"temperature": "51-62", "height":"1000-1500" ...... }

所有键和值都是字符串类型。每个键都可以映射到许多可能值之一。现在我想将此字典转换为 numpy 数组/向量。我有以下顾虑:

  • 每个键对应于数组中的一个索引位置。
  • 每个可能的字符串值都映射到一个整数。
  • 对于某些字典,某些键不可用。例如,我还有一个没有“温度”键的字典,因为该网页不包含此类字段。

我想知道在 Python 中编写这种转换的最清晰和最有效的方法是什么。我正在考虑构建另一个字典,将键映射到向量的索引号。以及将值映射到整数的许多其他字典。

我遇到的另一个问题是我不确定某些键的范围。我想动态跟踪字符串值和整数之间的映射。例如,我可能会发现 key1 将来可以映射到 val1_8。

谢谢

【问题讨论】:

标签: python numpy dictionary


【解决方案1】:

试试 pandas 系列,它就是为此而生的。

import pandas as pd
s = pd.Series({'a':1, 'b':2, 'c':3})
s.values # a numpy array

【讨论】:

  • 一个问题是不是所有字典都有相同的键集,熊猫可以处理这个吗?谢谢
  • 是的。您可能还想查看 pandas DataFrame 以获得更多乐趣。
  • 谢谢,我安装了它,真正强大的工具。我做了 pd.DataFrame( {dd["name"]: pd.Series( dd) for dd in dictlist}) ,其中 dictlist 是字典列表。
【解决方案2】:
>>> # a sequence of dictionaries in an interable called 'data'
>>> # assuming that not all dicts have the same keys
>>> pprint(data)
  [{'x': 7.0, 'y1': 2.773, 'y2': 4.5, 'y3': 2.0},
   {'x': 0.081, 'y1': 1.171, 'y2': 4.44, 'y3': 2.576},
   {'y1': 0.671, 'y3': 3.173},
   {'x': 0.242, 'y2': 3.978, 'y3': 3.791},
   {'x': 0.323, 'y1': 2.088, 'y2': 3.602, 'y3': 4.43}]

>>> # get the unique keys across entire dataset
>>> keys = [list(dx.keys()) for dx in data]

>>> # flatten and coerce to 'set'
>>> keys = {itm for inner_list in keys for itm in inner_list}

>>> # create a map (look-up table) from each key 
>>> # to a column in a NumPy array

>>> LuT = dict(enumerate(keys))
>>> LuT
  {'y2': 0, 'y3': 1, 'y1': 2, 'x': 3}

>>> idx = list(LuT.values())

>>> # pre-allocate NUmPy array (100 rows is arbitrary)
>>> # number of columns is len(LuT.keys())

>>> D = NP.empty((100, len(LuT.keys())))

>>> keys = list(LuT.keys())
>>> keys
  [0, 1, 2, 3]

>>> # now populate the array from the original data using LuT
>>> for i, row in enumerate(data):
        D[i,:] = [ row.get(LuT[k], 0) for k in keys ]

>> D[:5,:]
  array([[ 4.5  ,  2.   ,  2.773,  7.   ],
         [ 4.44 ,  2.576,  1.171,  0.081],
         [ 0.   ,  3.173,  0.671,  0.   ],
         [ 3.978,  3.791,  0.   ,  0.242],
         [ 3.602,  4.43 ,  2.088,  0.323]])

将最后的结果(D 的前 5 行)与上面的 数据进行比较

请注意,每行(单个字典)的排序保留了一组不完整的键 - 换句话说,第 2 列 D 始终 对应于键入到 y2、 等的值,即使数据中的给定行没有为该键存储的值; eg,看data的第三行,只有两个key/value对,在D的第三行,第一列和最后一列都是0,这些列对应keys xy2,实际上是缺少的两个键

【讨论】:

  • 感谢您的详细回答。我发现 Pandas 是解决我当前问题的自然方法。
猜你喜欢
  • 2018-05-28
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 2011-12-11
  • 2011-01-14
  • 2020-08-22
相关资源
最近更新 更多