简体   繁体   English

python 字典到 numpy 数组切片

[英]python dictionary to numpy array slicing

I have a dictionary.我有一本字典。

cars_dict= { 'cars_per_cap': [809, 731, 588, 18, 200, 70, 45], 'country': ['United States','Australia','Japan','India','Russia','Morocco','Egypt'], 'drives_right': [True, False, False, False, True, True, True] }

I changed it into NumPy by doing我通过这样做将其更改为 NumPy

cars_numpy = np.array(cars_dict)

cars_numpy = array({'cars_per_cap': [809, 731, 588, 18, 200, 70, 45], 'country': ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt'], 'drives_right': [True, False, False, False, True, True, True]}, dtype=object)

I want to do slicing and get 'United states' from it我想做切片并从中得到“美国”

print(cars_numpy[1][0]) is not working. print(cars_numpy[1][0])不工作。

error I get is this我得到的错误是这个


IndexError                                Traceback (most recent call last)
<ipython-input-121-54a4195f7446> in <module>
----> 1 print(cars_numpy[1][0])

IndexError: too many indices for array

Dictionary is not a list, you cant pass it to numpy and expect the same results, its not ordered, it uses an internal data structure in order to be efficient.字典不是列表,您不能将其传递给 numpy 并期望得到相同的结果,它没有排序,它使用内部数据结构以提高效率。

What you could do is:你可以做的是:

cars_numpy = np.array(list(cars_dict.values()))

Which will put them into an array, but you cannot guarantee the order between the keys using this method, eg the row of country might be before cars_per_cap .这会将它们放入一个数组中,但是您不能保证使用此方法的键之间的顺序,例如country行可能在cars_per_cap之前。

I have a few things to suggest -我有几点建议——

  1. You need a nested list instead of a dictionary to create a multi-dim NumPy array.您需要嵌套列表而不是字典来创建多维度 NumPy 数组。 This is available using list(dictionary.values()) .这可以使用list(dictionary.values())获得。
  2. Using np.array(dictionary) will give you a NumPy array with a single entry that holds the dict.使用np.array(dictionary)将为您提供一个 NumPy 数组,其中包含一个包含字典的条目。 Therefore the error IndexError: too many indices for array because you are asking for a row and column, but it only has a single element at arr[0]因此错误IndexError: too many indices for array因为您要的是行和列,但它在arr[0]只有一个元素
  3. arr[1][0] is a highly inefficient way of using numpy. arr[1][0]是使用 numpy 的一种非常低效的方式。 Instead, try arr[1,0]相反,请尝试arr[1,0]
  4. Dictionaries are now insertion ordered.字典现在是插入排序的。 As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted.从 Python 3.6 开始,对于 Python 的 CPython 实现,字典会记住插入项目的顺序。 Changing them to numpy arrays (their values() ) will retain this order.将它们更改为 numpy arrays (它们的values() )将保留此顺序。

Therefore this would work -因此这将起作用 -

np.array(list(cars_dict.values()))[1,0]
'United States'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM