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

Extract values from two columns of a dataframe and put it in a list

I have a dataframe as shown below:

df = 

 A  col_1   col_45   col_3
1.0   4.0    45.0    [1, 9]
2.0   4.0    NaN     [9, 10]
3.0   49.2   10.8    [1, 10]

The values in col_1 are of type float and the values in col_3 are in a list. For every row, I want to extract the values in col_1 and col_3 and put it together in a list.

I tried the following:

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

df[['col_1','col_3']].astype(float).values.tolist()

But it threw me a Value error: ValueError: setting an array element with a sequence..

I would like to have a list as follows:

[[4.0,1.0,9.0],
 [4.0,9.0,10.0],
 [49.2,1.0,10.0]]

Is there a way to do this?
Thanks.

>Solution :

Convert one element in col_1 to list then use merge two list like list_1 + list_2, You can use pandas.apply with axis=1 for iterate over each row:

>>> df.apply(lambda row: [row['col_1']] + row['col_3'], axis=1)
0      [4.0, 1, 9]
1     [4.0, 9, 10]
2    [49.2, 1, 10]
dtype: object

>>> df.apply(lambda row: [row['col_1']] + row['col_3'], axis=1).to_list()
[
    [4.0, 1, 9], 
    [4.0, 9, 10], 
    [49.2, 1, 10]
]
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