📜  将Python字典转换为 NumPy 数组的不同方法

📅  最后修改于: 2022-05-13 01:55:41.205000             🧑  作者: Mango

将Python字典转换为 NumPy 数组的不同方法

在本文中,我们将看到使用 NumPy 库将Python字典转换为 Numpy 数组的不同方法。有时需要将Python中的字典转换为 NumPy 数组, Python提供了一种有效的方法来执行此操作。将字典转换为 NumPy 数组会生成一个包含字典键值对的数组。

让我们看看不同的方法:

方法一: numpy.array()List Comprehension一起使用。

我们使用np.array()将字典转换为 nd 数组。并且为了将字典的每个值作为输入到 np.array() 的列表,使用了列表理解的概念。

例子:

Python3
# importing required librariess
import numpy as np
from ast import literal_eval
  
# creating class of string
name_list = """{
   "column0": {"First_Name": "Akash",
   "Second_Name": "kumar", "Interest": "Coding"},
                  
   "column1": {"First_Name": "Ayush",
   "Second_Name": "Sharma", "Interest": "Cricket"},
     
   "column2": {"First_Name": "Diksha",
   "Second_Name": "Sharma","Interest": "Reading"},
     
   "column3": {"First_Name":" Priyanka",
   "Second_Name": "Kumari", "Interest": "Dancing"}
     
  }"""
print("Type of name_list created:\n",
      type(name_list))
  
# converting string type to dictionary
t = literal_eval(name_list)
  
# printing the original dictionary
print("\nPrinting the original Name_list dictionary:\n",
      t)
  
print("Type of original dictionary:\n",
      type(t))
  
# converting dictionary to numpy array
result_nparra = np.array([[v[j] for j in ['First_Name', 'Second_Name',
                                          'Interest']] for k, v in t.items()])
  
print("\nConverted ndarray from the Original dictionary:\n",
      result_nparra)
  
# printing the type of converted array
print("Type:\n", type(result_nparra))


Python3
# importing library
import numpy as np
  
# creating dictionary as key as 
# a number and value as its cube
dict_created = {0: 0, 1: 1, 2: 8, 3: 27,
                4: 64, 5: 125, 6: 216}
  
# printing type of dictionary created
print(type(dict_created))
  
# converting dictionary to 
# numpy array 
res_array = np.array(list(dict_created.items()))
  
# printing the converted array
print(res_array)
  
# printing type of converted array
print(type(res_array))


输出:

方法 2:使用numpy.array( ) 和dictionary_obj.items()

我们使用np.array()将字典转换为 nd 数组。为了将字典的每个值作为 np.array() 方法的输入列表,使用了dictionary_obj.items()

例子:

Python3

# importing library
import numpy as np
  
# creating dictionary as key as 
# a number and value as its cube
dict_created = {0: 0, 1: 1, 2: 8, 3: 27,
                4: 64, 5: 125, 6: 216}
  
# printing type of dictionary created
print(type(dict_created))
  
# converting dictionary to 
# numpy array 
res_array = np.array(list(dict_created.items()))
  
# printing the converted array
print(res_array)
  
# printing type of converted array
print(type(res_array))

输出:


[[  0   0]
[  1   1]
[  2   8]
[  3  27]
[  4  64]
[  5 125]
[  6 216]]