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

Pandas如何按条件合并DataFrame数组列:非空时追加column_2到column_1后删列

Pandas 实现方案

直接按行判断column_2是否为空,非空就做数组拼接,最后删列就行,代码如下:

import pandas as pd
import numpy as np

# 初始化示例DataFrame
df = pd.DataFrame({
    'column_1': [[1,3], [1,2,3], [3,4]],
    'column_2': [[2], np.nan, [6]],
    'column_3': [2, 1, 1]
})

# 核心处理:非空时把column_2的元素追加到column_1
df['column_1'] = df.apply(
    lambda x: x['column_1'] + x['column_2'] if pd.notnull(x['column_2']) else x['column_1'],
    axis=1
)

# 删除不需要的column_2列
df = df.drop('column_2', axis=1)

执行后得到的结果完全匹配预期:

column_1  column_3
0  [1, 3, 2]         2
1  [1, 2, 3]         1
2  [3, 4, 6]         1

如果是Spark SQL场景下的DataFrame,逻辑完全一致:用when().otherwise()判断column_2是否为null,非null时用concat函数拼接两个数组,最后drop掉column_2即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 23:45:36