Pandas:根据另一列字符串修改列值的问题求助
问题描述
我有一个包含两列的DataFrame,一列是产品名称SKU Name,另一列是产品数量Quantity_SKU,数据如下:
| SKU Name | Quantity_SKU |
|---|---|
| Box chocolate 24 unds | 1 |
| Box chocolate 12 unds | 1 |
| Box Apple and Bananas 24 unds | 1 |
| Box Apple and Bananas 12 unds | 1 |
| Apple and Bananas | 1 |
| chocolate | 1 |
部分SKU实际包含多个单位,但Quantity_SKU列仅计数为1。需要实现规则:当SKU Name中出现“24 unds”时,将对应数量改为24;出现“12 unds”时改为12。
尝试用列表推导式实现时出现语法错误,代码如下:
df["units"] = [ 24 if ( (x == "Box chocolate 24 unds") or (x == "Box Apples e Bananas 24 unds") ) 12 ( if (x == "Box chocolate 12 unds") or (x == "Box Apples e Bananas 12 unds") ) else 800 for x in df["SKU Name"] ]
解决方案
1. 修正列表推导式语法
你的列表推导式存在语法错误,正确的嵌套条件写法如下,同时优化匹配逻辑(直接检查子串,无需逐个枚举SKU):
df["units"] = [ 24 if "24 unds" in x else 12 if "12 unds" in x else 1 # 用原数量1作为默认值 for x in df["SKU Name"] ]
如果需要保留原Quantity_SKU列的值作为默认,可修改为:
df["units"] = [ 24 if "24 unds" in x else 12 if "12 unds" in x else df["Quantity_SKU"].iloc[i] for i, x in enumerate(df["SKU Name"]) ]
2. pandas内置方法实现(更高效)
使用str.contains结合numpy.where,直接对整列操作,更符合pandas风格:
import numpy as np df["units"] = np.where( df["SKU Name"].str.contains("24 unds"), 24, np.where( df["SKU Name"].str.contains("12 unds"), 12, df["Quantity_SKU"] ) )
3. 扩展性方案(支持任意数字)
如果未来可能出现其他类似格式的SKU(如"36 unds"),可以用正则提取数字,无需新增条件:
# 提取"数字+unds"中的数字,无匹配则用原数量 df["units"] = df["SKU Name"].str.extract(r'(\d+) unds').fillna(df["Quantity_SKU"]).astype(int)
内容的提问来源于stack exchange,提问作者Júlio Cesar Gomes
相关产品推荐
相关产品推荐

