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

How to convert a DataFrame to a List?

I have a DataFrame with three columns. I want to convert this DataFrame to a python List.

DataFrame:

    name       year   value  
0   val_1      2001      3      
1   val_1      2002      3  
2   val_2      2001      0    
3   val_2      2002      3  
4   val_3      2001      3  
5   val_3      2002      0
6   val_4      2001      np.nan

List:

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

[['val_1', [[2001, 3], [2002, 3]]], ['val_2', [[2001, 0], [2002, 3]]], ['val_3', [[2001, 3], [2002, 0]]], ['val_4', []]]

An attempt:

[[k, list(g.values[:, 1:].tolist())] for k, g in df.groupby('value')]

(I struggle to deal with the np.nan)

>Solution :

Try:

>>> [[k, v.drop("name",axis=1).dropna().astype('int').to_numpy().tolist()] for k, v in df.groupby('name')]

[['val_1', [[2001, 3], [2002, 3]]],
 ['val_2', [[2001, 0], [2002, 3]]],
 ['val_3', [[2001, 3], [2002, 0]]],
 ['val_4', []]]
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