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