I have a data frame and each values is a list (or array). I want to convert the data frame to a list as follow.
Can you help me with that? Here is an example.
import pandas as pd
a = pd.DataFrame()
a['0'] = [[[0.2,0.4]], [[1, 10]]]
a['1'] = [[[4, 5]], [[6, 7]]]
0 1
[[0.2, 0.4]] [[4, 5]]
[[1, 10]] [[6, 7]]
and the output is:
import numpy as np
list_of_array = [ [np.array([[0.2, 0.4]]),np.array([[4, 5]])],[np.array([[1, 10]]),np.array([[6, 7]])]]
[[array([[0.2, 0.4]]), array([[4, 5]])], [array([[ 1, 10]]), array([[6, 7]])]]
>Solution :
You could use df.values.tolist() to get the dataframe as a list:
> df.values.tolist()
[[[0.2, 0.4]], [[4, 5]]], [[[1, 10]], [[6, 7]]]]
If you want the inner lists to be arrays then:
> list(map(list, map(np.array, a.values.tolist())))
[[array([[0.2, 0.4]]), array([[4, 5]])], [array([[ 1, 10]]), array([[6, 7]])]]
You could even just turn df.values to a list but the dtypes wouldn’t be converted the same from what I’m seeing. This isn’t exactly recommended:
> list(a.values)
[[array([[0.2, 0.4]]), array([[4., 5.]])], [array([[ 1, 10]]), array([[6, 7]])]]