Pandas:借助字典将变量子串从A列插入B列

2024-09-20 23:00:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个pandas数据帧:

df = pd.DataFrame(["LONG AAPL 2X CBZ","SHORT GOOG 10X VON"], columns=["Name"])

我想在列Name中标识"AAPL",通过字典"AAPL":"Apple"传递它,然后将其插入到新列Description中的字符串中。在

期望输出:

^{pr2}$

我遇到问题的地方是在另一个字符串中输入一个变量子字符串作为"Tracks X with Y leverage."

如果不需要这样做,只需从name提取到{}是可能的:

df["Description"] = df["Name"].str.extract(r"\s(\S+)\s").map({"AAPL":"Apple", "GOOG":"Google"})

或利用:

df["Description"] = df["Name"].str.extract(r"(\d+X)")

如果可能的话,我希望使用regex来提取变量,因为实际上我将做一些更详细的regex,例如检索不同格式的乘法器,例如X22x等等。在

另外一个{/strong>用<{/strong>在前面加上一个{/strong>来决定是否用{cdstrong>作为前一列的{

df["direction"] = df["name"].map(lambda x: "Long" if "LONG" in x else "Short" if "SHORT " in x else "Long")

Name                   Direction      Description
"LONG AAPL 2X CBZ"     "Long"         "Tracks Apple with 2X leverage."
"SHORT GOOG 10X VON"   "Short"        "Tracks Google with -10X leverage."

Tags: 字符串nameappledfwithdescriptionlonggoog
2条回答

您可以定义一个显式函数来应用于整个Name系列。在

df = pd.DataFrame(["LONG AAPL 2X CBZ","SHORT GOOG 10X VON"], columns=["Name"])

dmap = {"AAPL":"Apple", "GOOG":"Google"}
signmap = {"LONG": "", "SHORT": "-"}

def f(strseries):
    company = strseries.str.extract(r"\s(\S+)\s").map(dmap)
    leverage = strseries.str.extract(r"(\d+X)")
    sign = strseries.str.extract(r"(\S+)\s").map(signmap)
    return "Tracks " + company + " with " + sign + leverage + " leverage."

df['Description'] = f(df['Name'])

编辑:以牺牲可读性为代价,一次执行regex提取可以加快大约2倍的速度。在

^{pr2}$

因为我们只关心前两个子串和倒数第二个子串:

df = pd.DataFrame(["LONG AAPL 2X CBZ", "SHORT GOOG 10X VON", "BULL AXP UN X3 VON","LONG AXP X3 VON"], columns=["Name"])

maps = {"AAPL": "Apple", "GOOG": "Google"}
signs = {"SHORT": "-"}

def split(i):
    spl = i.split()
    a, b, c = spl[0], spl[1], spl[-2]
    val = maps.get(b, b) # if name is not to be replaced keep original
    return "Tracks  {} with {}{} leverage".format(val, signs.get(a, ""), c)

df["Description"]  = df["Name"].map(split)

输出:

^{pr2}$

只是拆分比使用正则表达式更有效:

In [33]: df2 = pd.concat([df]*10000)
In [34]: timeit  df2["Name"].map(split)
10 loops, best of 3: 57.5 ms per loop

In [35]: timeit f2(df2['Name'])
10 loops, best of 3: 168 ms per loop

如果你想添加更多的单词来替换,只需将它们添加到地图中,并用符号来表示。在

相关问题 更多 >

    热门问题