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

如何在已有DataFrame中新增int64类型的NA值列?

解决方案:新增支持NA的整数类型列到DataFrame

你的代码存在几个关键问题:

  • 尝试访问不存在的列df['new_col']会触发KeyError
  • fillna()未传入必填的填充值参数,语法不合法
  • 错误使用dtype('int64')指定类型,正确的类型转换方式是astype()

需要明确:numpy原生的int64类型无法存储缺失值,如果用np.nan填充,列会自动转为float64。如果要保留整数类型并支持NA,必须使用pandas的Nullable整数类型Int64(大写字母I)。

方法一:高效创建新列(适配大型DataFrame)

直接赋值并指定Int64 dtype,无需创建额外列表,性能更优:

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({'col1': [5, 7, 6], 'col2': ['s', 'g', 'f']})

# 新增new_col列,默认填充NA,指定类型为Int64
df['new_col'] = pd.Series(dtype='Int64')

方法二:使用assign()链式操作

适合需要保留原DataFrame不变的场景:

df = df.assign(new_col=pd.Series(dtype='Int64'))

验证结果

执行后查看DataFrame和列类型:

print(df)
print("\n列类型:", df['new_col'].dtype)

输出如下:

col1 col2 new_col
0     5    s    <NA>
1     7    g    <NA>
2     6    f    <NA>

列类型: Int64

如果业务场景必须使用numpy的int64类型(不支持缺失值),只能用固定值(如0)填充,无法保留NA,代码示例:

df['new_col'] = 0
df['new_col'] = df['new_col'].astype('int64')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:50:25