如何在Pandas中按条件创建新列fruit_cost并赋值?
Pandas实现类似SQL CASE WHEN的列赋值操作
我有一个Pandas DataFrame对象
df,想要创建新列fruit_cost:当item_type字段值为'fruit'时,该列取cost列的整数值;否则赋值为0。想了解Pandas中的标准实现方式,是用条件逻辑还是更简便的方法,同时希望获取此类操作的最佳实践。对应的SQL实现示例:
case when item_type = 'fruit' then cost else 0 end as fruit_cost我尝试的Python代码(存在语法错误):
import pandas as pd list_of_customers =[ ['patrick','lemon','fruit',10], ['paul','lemon','fruit',20], ['frank','lemon','fruit',10], ['jim','lemon','fruit',20], ['wendy','watermelon','fruit',39], ['greg','watermelon','fruit',32], ['wilson','carrot','vegetable',34], ['maree','carrot','vegetable',22], ['greg','','',], ['wilmer','sprite','drink',22] ] df = pd.DataFrame(list_of_customers,columns = ['customer','item','item_type','cost']) print(df) #create new field 'fruit_cost' df[fruit_cost] = if df[item_type] == 'fruit': df[cost] else: 0
标准实现方法
1. 使用numpy.where(最贴近SQL CASE逻辑)
这是最直观的写法,和SQL的CASE WHEN逻辑完全对应,适合简单条件判断:
import numpy as np df['fruit_cost'] = np.where(df['item_type'] == 'fruit', df['cost'], 0)
解释:第一个参数是判断条件,满足时取第二个参数的值,不满足则取第三个参数的值。
2. 使用Pandas原生where/mask方法
Pandas的Series自带where和mask方法,逻辑互补:
where:满足条件时保留原值,不满足时替换为指定值mask:不满足条件时替换为指定值,满足时保留原值
用where实现需求:
df['fruit_cost'] = df['cost'].where(df['item_type'] == 'fruit', 0)
用mask实现等价逻辑:
df['fruit_cost'] = df['cost'].mask(df['item_type'] != 'fruit', 0)
3. 使用loc索引赋值
适合复杂条件或需要分步操作的场景,可读性更强:
# 先初始化所有值为0 df['fruit_cost'] = 0 # 给满足条件的行赋值为cost列的值 df.loc[df['item_type'] == 'fruit', 'fruit_cost'] = df['cost']
这种方式便于扩展多条件分支,维护成本低。
空值处理注意事项
你的原始数据中存在空值行(比如greg的那一行),默认情况下空的item_type会被判定为不满足条件,自动赋值0。如果需要规避空值cost的影响,可以在条件中增加非空判断:
df['fruit_cost'] = np.where( df['item_type'].eq('fruit') & df['cost'].notna(), df['cost'], 0 )
最佳实践总结
- 简单单条件:优先用
numpy.where或Pandas的where方法,代码简洁直观,贴近SQL逻辑 - 多条件分支:嵌套
numpy.where或用loc分步赋值,更易维护 - 性能优化:大数据量下,以上方法的性能差异极小,均远快于循环遍历
- 可读性:优先选择贴近业务逻辑的写法,降低团队协作的理解成本
内容的提问来源于stack exchange,提问作者Patty
相关产品推荐
相关产品推荐

