[英]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 -我有几点建议——
list(dictionary.values())
.list(dictionary.values())
获得。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]
只有一个元素arr[1][0]
is a highly inefficient way of using numpy. arr[1][0]
是使用 numpy 的一种非常低效的方式。 Instead, try arr[1,0]
arr[1,0]
values()
) will retain this order.values()
)将保留此顺序。 Therefore this would work -因此这将起作用 -
np.array(list(cars_dict.values()))[1,0]
'United States'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.