![](/img/trans.png)
[英]Create a new column with [0,1] based on match between two rows in Python
[英]Python Add in new rows with new data based on Partial Match
表格1
|Location|Type|Supplier| ID |Serial|
| MAB |Ant | A | A123 |456/56|
| MEB |Ant | B | A123 |456/56|
表 2
|Location |Type|Supplier| ID |Serial|#####|
| MAB+MEB |Ant | A/B | A123 |456/56|123-4|
| MAB+MEB |Ant | A/B | A123/B123 |456/56|432-1|
| MAB+MEB |Ant | A/B | A123/B123 |456/56|432-1|
表3
|Location|Type|Supplier| ID |Serial|#####|
| MAB |Ant | A | A123 |456/56|123-4|
| MAB |Ant | A | A123 |456/56|432-1|
| MAB |Ant | A | A123 |456/56|432-1|
| MEB |Ant | B | A123 |456/56|123-4|
| MEB |Ant | B | A123 |456/56|432-1|
| MEB |Ant | B | A123 |456/56|432-1|
如上所示,如果表 1 列 'Location' 、 'Supplier' 、 'ID' 、 'Serial' 單元格內容包含在表 2 的相同列單元格中,則生成表 3。
*請注意,表 1 用作核心模板,如果表 2 中包含相關列單元格,我們只是復制表 1 中的行並將“####”列添加到每一行。
請建議我們如何生成表 3。
我的邏輯:對於表 1 中的 a、b、c、d,如果表 2 中包含 a、b、c、d,則按列將表 2 中的“Subcon Part #”附加到表 1,連接所有“Subcon Part #”通過 ',' 分解連接的 'Subcon Part #' 以生成具有唯一 'Subcon Part #' 的行
其中 a,b,c,d 是興趣列,表 1 和表 2 之間的鏈接
這是我的建議,首先從表 2 中提取值,然后將這個轉換后的 DataFrame 與表 1 中感興趣的變量合並:
首先,我重現你的例子:
import pandas as pd
import re
# reproducing table 1
df1 = pd.DataFrame({"Location": ["MAB", "MEB"],
"Type" : ["Ant", "Ant"],
"Supplier":["A","B"],
"ID": ["A123","A123"],
"Serial": ["456/56","456/56"]})
# then table 2
df = pd.DataFrame({"Location": ["MAB+MEB", "MAB+MEB", "MAB+MEB"],
"Type": ["Ant", "Ant", "Ant"],
"Supplier": ["A/B", "A/B","A/B"],
"ID": ["A123", "A123/B123", "A123/B123"],
"Serial":['456/56','456/56','456/56'],
"values_rand":[1,2,3]})
# First I split the column I am interested in based on regexp you can tweak according
# to what you want:
r = re.compile(r"[a-zA-Z0-9]+")
df['Supplier'], df["ID"], df["Location"] = df['Supplier'].str.findall(r),\
df['ID'].str.findall(r), \
df['Location'].str.findall(r)
table2 = pd.merge(df['Supplier'].explode().reset_index(),
df["ID"].explode().reset_index(),on="index", how="outer")
table2 = pd.merge(table2, df["Location"].explode().reset_index(),
on="index", how="outer")
table2 = pd.merge(table2, df.loc[:,["Type","Serial",
"values_rand"]].reset_index(), on="index",how="left")
result = (pd.merge(table2,df1, on=['Location' , 'Supplier' , 'ID' , 'Serial',"Type"])
.drop(columns="index"))
結果是
Supplier ID Location Type Serial values_rand
0 A A123 MAB Ant 456/56 1
1 A A123 MAB Ant 456/56 2
2 A A123 MAB Ant 456/56 3
3 B A123 MEB Ant 456/56 1
4 B A123 MEB Ant 456/56 2
5 B A123 MEB Ant 456/56 3
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.