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

如何为Pandas无列名的列分配递增数值?现有代码未生效

解决Pandas DataFrame中NaN列名替换问题

问题说明

需要将DataFrame中列名为NaN的列替换为1、2、3……的递增数值,已有列名保持不变;当前数据从第28列(索引27)开始列名为NaN,但编写的代码未能成功修改列名。

用户错误代码

import pandas as pd
import numpy as np

# 尝试为第28列及以后的NaN列名分配数字
df.iloc[:, 27:].columns = range(1, df.iloc[:, 27:].shape[1] + 1)
df.columns

原始列名输出

执行df.columns得到的原始列名:

Index([               'strand',                 'start',
                        'stop',          'total_probes',
             'gene_assignment',       'mrna_assignment',
                   'swissprot',               'unigene',
       'GO_biological_process', 'GO_cellular_component',
       'GO_molecular_function',               'pathway',
             'protein_domains',         'crosshyb_type',
                    'category',               'seqname',
                  'Gene Title',              'Cytoband',
                 'Entrez Gene',            'Swiss-Prot',
                     'UniGene', 'GO Biological Process',
       'GO Cellular Component', 'GO Molecular Function',
                     'Pathway',       'Protein Domains',
                    'Probe ID',                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan,
                           nan,                     nan],
      dtype='object', name=0)

期望列名输出

期望修改后的列名:

Index([               'strand',                 'start',
                        'stop',          'total_probes',
             'gene_assignment',       'mrna_assignment',
                   'swissprot',               'unigene',
       'GO_biological_process', 'GO_cellular_component',
       'GO_molecular_function',               'pathway',
             'protein_domains',         'crosshyb_type',
                    'category',               'seqname',
                  'Gene Title',              'Cytoband',
                 'Entrez Gene',            'Swiss-Prot',
                     'UniGene', 'GO Biological Process',
       'GO Cellular Component', 'GO Molecular Function',
                     'Pathway',       'Protein Domains',
                    'Probe ID',                     1,
                             2,                     3,
                             4,                     5,
                             6,                     7,
                             8,                     9,
                             10,                     11,
                             12,                     13,
                             14,                     15,
                             16,                     17,
                             18,                     19,
                             20,                     21,
                             22,                     23,
                             24,                     25,
                             26,                     27,
                             28,                     29],
      dtype='object', name=0)

问题原因

直接通过df.iloc[:, 27:].columns赋值无法修改原DataFrame的列名,因为iloc返回的是数据视图或副本,这种局部赋值操作不会同步到原DataFrame对象上。

解决方法

方法一:全局替换所有NaN列名

该方法无需依赖列的位置,自动识别所有列名为NaN的列并替换:

import pandas as pd

# 将列名转为列表以便修改
cols = df.columns.tolist()
# 生成对应数量的递增数字标签
num_labels = range(1, sum(pd.isna(col) for col in cols) + 1)
# 遍历替换所有NaN列名
nan_idx = 0
for i in range(len(cols)):
    if pd.isna(cols[i]):
        cols[i] = num_labels[nan_idx]
        nan_idx += 1
# 重新赋值给DataFrame的列名
df.columns = cols

方法二:针对指定列范围替换

已知从索引27开始为NaN列名,可直接修改该范围的列名:

# 将列名转为列表
cols = df.columns.tolist()
# 替换索引27及以后的列名为1开始的递增数字
cols[27:] = range(1, len(cols[27:]) + 1)
# 重新赋值列名
df.columns = cols

执行上述任意一种方法后,调用df.columns即可得到期望的列名结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:06:32