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

Python处理DataFrame空列表时如何返回None生成目标元组列表

解决方法

问题原因

你现有代码的问题根源:当col2列为空列表时,range(len(df[col2][i])) 会生成空可迭代对象,内层循环直接跳过,因此不会生成对应行的元组。

修改方案

方案1:直接调整循环逻辑(和你原有写法兼容)

你可以在遍历每行时先判断列表是否为空,空列表时手动插入带None的元组,非空则遍历列表元素生成元组:

result = []
for i in range(len(df)):
    col1_val = df['col1'].iloc[i]
    col2_vals = df['col2'].iloc[i]
    if not col2_vals:
        result.append((col1_val, None))
    else:
        for v in col2_vals:
            result.append((col1_val, v))

如果要保留单行列表推导式的写法,可以调整内层迭代逻辑:

result = [(df['col1'].iloc[i], v) for i in range(len(df)) for v in (df['col2'].iloc[i] if df['col2'].iloc[i] else [None])]

方案2:使用Pandas内置方法(更简洁高效)

直接用Pandas的explode方法展开列表,空列表展开后会生成NaN,替换为None后直接转元组列表即可:

result = list(df.explode('col2').fillna({'col2': None}).itertuples(index=False, name=None))

两种方案运行后都可以得到你期望的输出:

[(909101, 1396920),
(909101, 3094857),
 (21095887, 8383568),
 (8383568, 21095887),
 (2408689, None)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:06:03