You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Pandas DataFrame单元格中的列表批量添加指定元素?

Why Your Previous Attempts Failed

Let's break down the issues with your code:

  • df['col2'] += [0,0]: This tries to add the list as new elements to the Series, not append to each cell's list. Pandas doesn't interpret this as per-row list concatenation.
  • df.col2.apply(lambda x: x.append([0,0])): list.append() modifies the list in-place and returns None, so you end up with a column full of None values instead of updated lists.
  • The assign attempt targeted the entire DataFrame instead of col2, and even if corrected, the + operator doesn't work as intended on a Series of lists.

Alternative: In-Place Modification (Use Carefully)

If you need to modify the original lists (not create new ones), use extend in a loop:

for lst in df['col2']:
    lst.extend([0, 0])

Note this changes the original lists outside the DataFrame if they're referenced elsewhere—this can cause unexpected side effects, so the first two methods are safer for most use cases.

内容的提问来源于stack exchange,提问作者Pasgru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:40:24