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

如何给Pandas DataFrame列表列的每个元素加整数并保留NaN

解决Pandas列表列元素加1并保留NaN的问题

给定如下Pandas DataFrame:

import pandas as pd
import numpy as np

d = {'id': {0: 0, 1: 1, 2: 2.0, 3: 3},
     'lst': {0: [1, 2], 1: [0], 2: [1, 2, 3], 3: np.nan}}
df = pd.DataFrame(d)
print(df)

输出:

id        lst
0  0.0     [1, 2]
1  1.0        [0]
2  2.0  [1, 2, 3]
3  3.0        NaN

需求是给lst列中每个列表的元素加1,同时保留NaN值,得到如下输出:

id        lst
0  0.0     [2, 3]
1  1.0        [1]
2  2.0  [2, 3, 4]
3  3.0        NaN

解决方案

方法1:使用apply结合lambda函数

通过判断值是否为NaN,对列表元素逐个加1:

df['lst'] = df['lst'].apply(lambda x: [i+1 for i in x] if pd.notna(x) else x)

方法2:通过类型判断处理

直接检查值是否为列表类型,避免NaN的干扰:

df['lst'] = df['lst'].map(lambda x: [i+1 for i in x] if isinstance(x, list) else x)

两种方法都能实现需求,执行后即可得到目标输出。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:01:54