Python – Create a DataFrame from a dictionary where the value of the dictionary is a numpy array

Create a DataFrame from a dictionary where the value of the dictionary is a numpy array… here is a solution to the problem.

Create a DataFrame from a dictionary where the value of the dictionary is a numpy array

I want to create a data frame from a dictionary where the values are a two-dimensional numpy array.

my_Dict={'a': array([[1, 2, 3],[4, 5, 6]]), 'b': array([[7,8,9],[10,11,12]]),'c': array([[13,14,15],[16,17,18]])}

I want the result to be a data frame with 2 rows (the number of rows in the numpy array) and 3 columns, as shown below:

       a         b          c

0  [1, 2, 3]   [7,8,9]    [13,14,15]

1  [4, 5, 6]  [10,11,12] [16,17,18]

I tried changing the value to list but it worked. But I want to keep these values as np arrays in order to apply the numby function to these values.

Solution

>>> list(np.array([[1, 2, 3],[4, 5, 6]]))
[array([1, 2, 3]), array([4, 5, 6])]
>>>

Converts a two-dimensional array of each column into a list of two one-dimensional arrays

d = {'a': np.array([[1, 2, 3],[4, 5, 6]]),
      'b': np.array([[7,8,9],[10,11,12]]),
      'c': np.array([[13,14,15],[16,17,18]])}

df = pd. DataFrame({k:list(v) for k,v in d.items()})

>>> df
           a             b             c
0  [1, 2, 3]     [7, 8, 9]  [13, 14, 15]
1  [4, 5, 6]  [10, 11, 12]  [16, 17, 18]
>>> 

>>> df.loc[0,'a']
array([1, 2, 3])
>>> df['a'].values
array([array([1, 2, 3]), array([4, 5, 6])], dtype=object)
>>> df.values
array([[array([1, 2, 3]), array([7, 8, 9]), array([13, 14, 15])],
       [array([4, 5, 6]), array([10, 11, 12]), array([16, 17, 18])]],
      dtype=object)
>>>

Related Problems and Solutions