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

为含随机索引的Pandas DataFrame新增行号列C

解决方案:给带随机索引的DataFrame添加行号列

嘿,这个需求很容易实现,用pandas的几种简单方法就能搞定!下面一步步来:

1. 先构造你的原始DataFrame(方便测试)

首先我们先把你给出的DataFrame用代码还原出来:

import pandas as pd

# 定义数据和随机索引
data = {
    'A': [0, 5, 0, 9, 10, 6],
    'B': [7, 4, 10, 8, 5, 2]
}
random_index = [100, 203, 5992, 2003, 20, 12]
df = pd.DataFrame(data, index=random_index)

此时的DataFrame是这样的:

A   B
100    0   7
203    5   4
5992   0  10
2003   9   8
20    10   5
12     6   2

2. 添加行号列'C'

这里有两种简洁的方式,效果完全一致:

方法一:使用Python内置的range()

直接利用DataFrame的长度生成从0开始的连续整数序列,赋值给新列'C':

df['C'] = range(len(df))

方法二:使用numpy的arange()

如果你的项目已经引入了numpy,也可以用这个方法:

import numpy as np
df['C'] = np.arange(len(df))

3. 最终结果

执行完上面的代码后,你的DataFrame就会变成你想要的样子:

A   B  C
100    0   7  0
203    5   4  1
5992   0  10  2
2003   9   8  3
20    10   5  4
12     6   2  5

这样就完美实现了给每一行添加从0开始的连续行号,完全不受原随机索引的影响~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:11:18