我有这个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,例如检索不同格式的乘法器,例如X2
,2x
等等。在
另外一个{/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."
您可以定义一个显式函数来应用于整个
Name
系列。在编辑:以牺牲可读性为代价,一次执行regex提取可以加快大约2倍的速度。在
^{pr2}$因为我们只关心前两个子串和倒数第二个子串:
输出:
^{pr2}$只是拆分比使用正则表达式更有效:
如果你想添加更多的单词来替换,只需将它们添加到地图中,并用符号来表示。在
相关问题 更多 >
编程相关推荐