I’m trying to conditionally append a list of lists in pandas:
import pandas as pd
df = pd.DataFrame(data={'A': [1, 2, 3]})
df['B'] = [[[1],[1],[1]]] * df.shape[0]
df
A B
0 1 [[1], [1], [1]]
1 2 [[1], [1], [1]]
2 3 [[1], [1], [1]]
# attempting to append 1st list of lists in B column with 2
df['B'] = df['B'].mask(df.A == 2, df['B'].apply(lambda x: x[0].append(2)))
df
A B
0 1 [[1, 2, 2, 2], [1], [1]]
1 2 None
2 3 [[1, 2, 2, 2], [1], [1]]
#expected result I'm hoping for is:
df['B'] = [[[1],[1],[1]],[[1,2],[1],[1]],[[1],[1],[1]]]
df
A B
0 1 [[1], [1], [1]]
1 2 [[1, 2], [1], [1]]
2 3 [[1], [1], [1]]
>Solution :
list.append works in place, so it actually returns None instead of a list. This is why your new df has None on the second row.
Below is a way to add 2 to the list. We take the first list in the second row and add [2], then unpack the rest of the lists to form the expected output:
df['B'].mask(df['A'].eq(2),lambda x: x.map(lambda x: [x[0] + [2],*x[1:]]))
Output:
0 [[1], [1], [1]]
1 [[1, 2], [1], [1]]
2 [[1], [1], [1]]