I have a pandas.DataFrame
like this:
id count fruit_list
---------------------------------------
0 42 [orange, apple]
1 57 [lemon]
2 86 [kiwi]
3 33 [pineapple, pear]
4 11 [apple, lemon]
...
I need to add new string to fruit_list
in every row. Let's say the string is banana
, so I need to end with DataFrame
like this:
id count fruit_list
---------------------------------------
0 42 [orange, apple, banana]
1 57 [lemon, banana]
2 86 [kiwi, banana]
3 33 [pineapple, pear, banana]
4 11 [apple, lemon, banana]
...
How can I do this most easily please?
Try apply
:
df['fruit_list'] = df['fruit_list'].apply(lambda x: x + ['banana'])
Sample:
df = pd.DataFrame({'count': [42, 57],
'fruit_list': [['orange', 'apple'], ['lemon']],
'id': [0, 1]}).reindex_axis(['id','count','fruit_list'], 1)
print (df)
id count fruit_list
0 0 42 [orange, apple]
1 1 57 [lemon]
df['fruit_list'] = df['fruit_list'].apply(lambda x: x + ['banana'])
print (df)
id count fruit_list
0 0 42 [orange, apple, banana]
1 1 57 [lemon, banana]
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.