简体   繁体   中英

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

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

Sample df:

Name List
Peter [a, bc]
George [d, ef]

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

Desired output:

Name List
Peter [a, bc]
George [d, ef, g, h]

Any suggestions?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM