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

conditionally append value to list of lists in pandas

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 :

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

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