(数据科学学习手札157)pandas新增case_when方法
本文示例代码已上传至我的
Github
仓库https://github.com/CNFeffery/DataScienceStudyNotes
1 简介
大家好我是费老师,pandas
在前不久更新的2.2
版本中,针对Series
对象新增了case_when()
方法,用于实现类似SQL
中经典的CASE WHEN
语句功能,今天的文章中,我们就来get其具体使用方法~

2 pandas中的case_when()新方法
首先请确保你的pandas
版本大于等于2.2
,在确保Python
版本大于等于3.9
的前提下,终端执行下列命令安装最新版本的pandas
:
pip install pandas -U
2.1 case_when()的使用
case_when()
作为Series
对象的方法,其参数非常简单只有一个caselist
,用于定义条件映射规则,格式如[(条件1, 替代值1), (条件2, 替代值2), ...]
,最基础的用法下,每个条件为与目标Series
长度相等的bool
值序列,譬如下面的例子:

更灵活的方式,是将条件写作可执行函数,譬如lambda
函数,进而引用自身实现灵活的条件判断:

函数式条件,在针对数据框进行链式分析的过程中,可以很灵活的基于上一步的临时计算状态,进行条件赋值操作,譬如(示例数据及代码见文章开头仓库地址):

更多有关case_when()
方法的介绍,请移步官方文档:https://pandas.pydata.org/docs/reference/api/pandas.Series.case_when.html
以上就是本文的全部内容,欢迎在评论区与我进行讨论~