gpt4 book ai didi

python - 如何将新元素添加到列表中的 pandas.DataFrame 列?

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:24 24 4
gpt4 key购买 nike

我有一个像这样的 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]
...

请问我怎样才能最轻松地做到这一点?

最佳答案

尝试应用:

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]

关于python - 如何将新元素添加到列表中的 pandas.DataFrame 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43386043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com