mercredi 5 février 2020

How can I append a different element for each list in a column in pandas?

I have a dataframe, df, with lists in a specific column, col_a. For example, consider that the first element is [1, 2, 3] and the second is [4, 5]. Please note that they can be lists of different lengths.

I want to use conditions on these lists and apply specific modifications, including appends. For example, imagine that if the length of the list is > 2, I want to append another element, that is the sum of the last two elements of the current list. So, considering the first list above, I have [1, 2, 3] and I want to have [1, 2, 3, 5].

What I tried to do was:

""" df.loc[:, col_a] = df[col_a].apply(lambda value: value.append(value[-2]+value[-1]) if len( value) > 1 else value) """

But the result in that column is "None" for all the elements of the column.

Can someone help me, please?

Thank you very much in advance.

Aucun commentaire:

Enregistrer un commentaire