【发布时间】:2022-01-25 16:38:58
【问题描述】:
以下是我正在使用的 Excel 工作表的示例:
| Product_Type | Part_Number | Description | Size |
|---|---|---|---|
| Rod | R-SS-015 | ||
| Rod | R-SS-030 | ||
| Rod | R-SS-045 | ||
| Rod | R-SS-060 | ||
| Rod | R-SS-075 | ||
| Rod | R-SS-090 | ||
| Nut | N-150 | Stainless Steel 1" Nut | |
| Nut | N-151 | Stainless Steel 2" Nut | |
| Nut | N-152 | Stainless Steel 3" Nut | |
| Washer | W-101 | Stainless Steel 1" Washer | |
| Washer | W-102 | Stainless Steel 2" Washer | |
| Washer | W-103 | Stainless Steel 3" Washer |
我要做的是从 Part_Number 中获取“杆”的尺寸,从描述中获取“螺母/垫圈”的尺寸。在 Excel 中,我会使用 IFS、搜索和左/中/右函数的组合。
我能够单独找到产品类型的尺寸,但无法连接到产品类型。
如:
"如果 Product_Type 等于 Rod,则搜索 Part_Number 并输出到 Size"
或
"如果 Product_Type 等于 Nut 或 Washer,则搜索 Description 并输出到 Size"
对于 Rod,我使用以下代码:
conditions = [
df.loc[df['Part_Number'].str.contains('-015'), 'Size'] == '1"',
df.loc[df['Part_Number'].str.contains('-030'), 'Size'] == '2"',
df.loc[df['Part_Number'].str.contains('-045'), 'Size'] == '3"',
df.loc[df['Part_Number'].str.contains('-060'), 'Size'] == '4"',
df.loc[df['Part_Number'].str.contains('-075'), 'Size'] == '5"',
df.loc[df['Part_Number'].str.contains('-090'), 'Size'] == '6"',
]
df['Size'] = np.select(df[Product_Type] == "Rod", conditions, '')
对于螺母/垫圈,我使用以下代码:
df_2 = df['Descritpion'].str.extract(r'(?:\s([\d+]?\.?[\d+])")', expand=False)
df['Size'] = np.where(df['Product_Type'] == "Nut" or df['Product_Type'] == "Washer", df_2, '')
对于这两个代码,我都收到以下错误:
ValueError:案例列表必须与条件列表长度相同
这是因为只有一个值(Rod)和多个条件(大小)正确吗?
如何将 str.extract 和 str.contains 结合起来?
【问题讨论】: