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

如何在Dask DataFrame中使用多条件进行标签标注?

在Dask中实现类似numpy.where()的多条件打标签功能

在Dask里有几种方式可以实现你需要的多条件打标签需求,和你用Pandas + np.where的逻辑完全兼容,下面是两种常用方案:

方案一:使用dask.array.where

Dask的数组模块dask.array提供了和numpy.where用法几乎一致的where函数,可直接在Dask DataFrame的列操作中使用,逻辑和你Pandas的写法完全对应:

import dask.dataframe as dd
import dask.array as da
import pandas as pd

# 构造Dask DataFrame
df = dd.from_pandas(pd.DataFrame({'Name':['A','B','C'],
                    'Sex':['Male','Female','Male'],
                    'Height':[175,160,195]}), npartitions=1)

# 初始化Tag列
df['Tag'] = ""
# 第一个条件赋值
df['Tag'] = da.where((df['Sex'] == "Male") & (df['Height'] > 180.), "CT", df['Tag'])
# 第二个条件赋值
df['Tag'] = da.where((df['Sex'] == "Female") & (df['Height'] <= 180.), "GT", df['Tag'])

# 计算并查看结果
print(df.compute())

方案二:使用dask.dataframe.case(更适合多条件场景)

如果后续需要添加更多条件,用case函数能让代码结构更清晰,它支持传入多组(条件, 对应标签)的元组,最后指定默认值即可:

import dask.dataframe as dd
import pandas as pd

# 构造Dask DataFrame
df = dd.from_pandas(pd.DataFrame({'Name':['A','B','C'],
                    'Sex':['Male','Female','Male'],
                    'Height':[175,160,195]}), npartitions=1)

# 多条件打标签
df['Tag'] = dd.case(
    [
        ((df['Sex'] == "Male") & (df['Height'] > 180.), "CT"),
        ((df['Sex'] == "Female") & (df['Height'] <= 180.), "GT")
    ],
    default=""
)

# 计算并查看结果
print(df.compute())

两种方案运行后都会得到和你Pandas示例完全一致的结果:

NameSexHeightTag
AMale175
BFemale160GT
CMale195CT

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:01:08