栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Pandas条件创建series/dataframe列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pandas条件创建series/dataframe列

如果你只有两种选择:

df['color'] = np.where(df['Set']=='Z', 'green', 'red')

例如,

import pandas as pdimport numpy as npdf = pd.Dataframe({'Type':list('ABBC'), 'Set':list('ZZXY')})df['color'] = np.where(df['Set']=='Z', 'green', 'red')print(df)

输出

  Set Type  color0   Z    A  green1   Z    B  green2   X    B    red3   Y    C    red

如果你有两个以上的条件,请使用

np.select
。例如,如果你想
color
成为

  • yellow
    when
    (df['Set'] == 'Z') & (df['Type'] == 'A')
  • otherwise
    blue
    when
    (df['Set'] == 'Z') & (df['Type'] == 'B')
  • otherwise
    purple
    when
    (df['Type'] == 'B')
  • otherwise
    black
    ,

然后使用

df = pd.Dataframe({'Type':list('ABBC'), 'Set':list('ZZXY')})conditions = [    (df['Set'] == 'Z') & (df['Type'] == 'A'),    (df['Set'] == 'Z') & (df['Type'] == 'B'),    (df['Type'] == 'B')]choices = ['yellow', 'blue', 'purple']df['color'] = np.select(conditions, choices, default='black')print(df)

输出:

  Set Type   color0   Z    A  yellow1   Z    B    blue2   X    B  purple3   Y    C   black


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369501.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号