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

如何为Dask DataFrame中column1的唯一值添加连续唯一ID新列

为Dask DataFrame分组分配连续唯一编号

针对你的需求,有两种简洁的实现方式:

方法一:手动生成映射字典

先提取column1的唯一值,创建值与编号的映射,再通过映射添加新列:

import dask.dataframe as dd
import pandas as pd

# 构造示例Dask DataFrame
pdf = pd.DataFrame({
    'column1': ['a', 'a', 'b', 'c', 'c'],
    'column2': [1, 2, 3, 4, 5]
})
ddf = dd.from_pandas(pdf, npartitions=1)

# 获取column1的唯一值并排序(可选,确保编号顺序符合预期)
unique_values = ddf['column1'].unique().compute().sort_values()
# 创建映射字典,编号从1开始
id_mapping = {val: idx + 1 for idx, val in enumerate(unique_values)}

# 添加新列column3
ddf['column3'] = ddf['column1'].map(id_mapping)

# 查看结果
print(ddf.compute())

方法二:利用分类类型编码

将column1转为分类类型,利用分类的codes属性生成编号(默认从0开始,加1后得到从1开始的连续编号):

import dask.dataframe as dd
import pandas as pd

# 构造示例Dask DataFrame
pdf = pd.DataFrame({
    'column1': ['a', 'a', 'b', 'c', 'c'],
    'column2': [1, 2, 3, 4, 5]
})
ddf = dd.from_pandas(pdf, npartitions=1)

# 转为分类类型并生成编号
ddf['column3'] = ddf['column1'].astype('category').cat.codes + 1

# 查看结果
print(ddf.compute())

两种方法都能得到你期望的输出:

column1  column2  column3
0       a        1        1
1       a        2        1
2       b        3        2
3       c        4        3
4       c        5        3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:46:00