How to append value to list in single cell in Pandas dataframe based on condition

Viewed 617

I want to append a value to a list in my dataframe based on a condition.

Sample df:

Name List
Peter [a, b c]
George [d, e f]

I want to add the values [g, h] to the list column if the name is George.

Desired output:

Name List
Peter [a, b c]
George [d, e f, g, h]

Any suggestions?

1 Answers

Use cutom lambda function for add values to lists by mask:

L = ['g','h']
m = df['Name'].eq('George')

df['List'] = df['List'].mask(m, df['List'].apply(lambda x: x + L))
print (df)
     Name             List
0   Peter        [a, b, c]
1  George  [d, e, f, g, h]

Or:

df.loc[m, 'List'] = df.loc[m, 'List'].apply(lambda x: x + L)

Or:

df['List'] = np.where(m, df['List'].apply(lambda x: x + L), df['List'])
Related