我有pandas.DataFrame
这样:
id count fruit_list
---------------------------------------
0 42 [orange, apple]
1 57 [lemon]
2 86 [kiwi]
3 33 [pineapple, pear]
4 11 [apple, lemon]
...
我需要在每行中向fruit_list
添加新字符串。假设字符串为banana
,所以我需要以DataFrame
结尾:
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]
...
我怎样才能最轻松地做到这一点?
答案 0 :(得分:4)
尝试apply
:
df['fruit_list'] = df['fruit_list'].apply(lambda x: x + ['banana'])
样品:
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]