[英]Equivalent of Excel IFS/Search functions in Python Pandas with 1 value and multiple conditions
以下是我正在使用的 Excel 工作表的示例:
產品類別 | 零件號 | 描述 | 尺寸 |
---|---|---|---|
桿 | R-SS-001 | ||
桿 | R-SS-002 | ||
桿 | R-SS-003 | ||
桿 | R-SS-004 | ||
桿 | R-SS-005 | ||
桿 | R-SS-006 | ||
堅果 | N-150 | 不銹鋼 1" 螺母 | |
堅果 | N-151 | 不銹鋼 2" 螺母 | |
堅果 | N-152 | 不銹鋼 3" 螺母 | |
墊圈 | W-101 | 不銹鋼 1" 墊圈 | |
墊圈 | W-102 | 不銹鋼 2" 墊圈 | |
墊圈 | W-103 | 不銹鋼 3" 墊圈 |
我要做的是從 Part_Number 中獲取“桿”的尺寸,從描述中獲取“螺母/墊圈”的尺寸。 在 Excel 中,我將使用 IFS、搜索和左/中/右功能的組合。
我能夠單獨找到產品類型的尺寸,但無法連接到產品類型。
如:
“如果 Product_Type 等於 Rod,則搜索 Part_Number 和 output 到 Size”
或者
“如果 Product_Type 等於 Nut 或 Washer,則搜索 Description 和 output 到 Size”
對於 Rod,我使用以下代碼:
conditions = [
df.loc[df['Part_Number'].str.contains('-001'), 'Size'] == '1"',
df.loc[df['Part_Number'].str.contains('-002'), 'Size'] == '2"',
df.loc[df['Part_Number'].str.contains('-003'), 'Size'] == '3"',
df.loc[df['Part_Number'].str.contains('-004'), 'Size'] == '4"',
df.loc[df['Part_Number'].str.contains('-005'), 'Size'] == '5"',
df.loc[df['Part_Number'].str.contains('-006'), '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?
這將對您的np.select()
示例稍作更改。 要做的關鍵是確保您的條件和替換都是相同長度的列表。
conditions = [
df['Product_Type'] == 'Rod',
df['Product_Type'] == 'Nut',
df['Product_Type'] == 'Washer'
]
replacements = [
df['Part_Number'].str.extract(r'-(\d+)$', expand=False),
df['Description'].str.extract(r'(\d+)"', expand=False),
df['Description'].str.extract(r'(\d+)"', expand=False),
]
df['Size'] = np.select(conditions, replacements, default=None).astype(int)
這給了我這個結果,在你的 dataframe 上:
Product_Type Part_Number Description Size
0 Rod R-SS-001 NaN 1
1 Rod R-SS-002 NaN 2
2 Rod R-SS-003 NaN 3
3 Rod R-SS-004 NaN 4
4 Rod R-SS-005 NaN 5
5 Rod R-SS-006 NaN 6
6 Nut N-150 Stainless Steel 1" Nut 1
7 Nut N-151 Stainless Steel 2" Nut 2
8 Nut N-152 Stainless Steel 3" Nut 3
9 Washer W-101 Stainless Steel 1" Washer 1
10 Washer W-102 Stainless Steel 2" Washer 2
11 Washer W-103 Stainless Steel 3" Washer 3
作為更靈活的替代方法,還有.apply(..., axis=1)
作為將 function 應用於每一行的一種方式。 然而,這種靈活性是以速度為代價的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.