假设你有下表:
标签名称 | 价值 |
---|---|
1P1132A | 0.0 |
1P1132B | 0.0 |
1P1133A | 0.0 |
1P1133B | 3.0 |
1P1133C | 2.0 |
1P1133D | 1.0 |
通过在 pandas 中执行一些转换,我得到一列按标签编号及其所有字母分组的标签(下面的代码和最终表格)
# Add a column for tag number (without letter)
pattern = re.compile(r"\d{1}P\d+")
df["TagNo"] = df["TagName"].apply(lambda x: re.search(pattern, x).group(0))
#Get letter tag
df["TagLetter"] = df["TagName"].apply(lambda x: re.sub(pattern, "", x))
#Group by TagNo. and TagLetter
df["PairRef"] = (
df
[["TagNo", "TagLetter"]]\
.groupby("TagNo")["TagLetter"]
.transform(lambda x: "/".join(sorted(set(x))))
)
df["PairRef"] = df["TagNo"] + " " + df["PairRef"]
改造后的桌子:
标签名称 | 价值 | 标签号 | 标签信 | PairRef |
---|---|---|---|---|
1P1132A | 0.0 | 1P1132 | A | 1P1132 A/B |
1P1132B | 0.0 | 1P1132 | 乙 | 1P1132 A/B |
1P1133A | 0.0 | 1P1133 | A | 1P1133 A/B/C/D |
1P1133B | 3.0 | 1P1133 | 乙 | 1P1133 A/B/C/D |
1P1133C | 2.0 | 1P1133 | C | 1P1133 A/B/C/D |
1P1133D | 1.0 | 1P1133 | D | 1P1133 A/B/C/D |
你会用 SQL 怎么做?
到目前为止,我知道如何创建列 TagNo 和 TagLetter(使用非常非常简单的查询),但我不知道如何创建列 PairRef。
SELECT TagName, AvgValue, SUBSTRING(TagName,1,len(TagName)-1) as TagNo, SUBSTRING(TagName, -1) as TagLetter from table