Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert dataframe to a specific list

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]])]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]])]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading