[英]Case insensitive dictionary for Pandas map lambda function
下面,我在函数中使用lambda x:
map
值map
到pandas
列,如果它们出现在字典benchmarks
。
在该示例中,符号"GOOG"
被映射为"Google"
到"full_name
”列。
我的问题是:如何对 dict 进行不区分大小写的检查? 因此,例如,即使"AAPL"
在字典中, "Aapl"
变成"Apple"
。
import pandas as pd
import re
df = pd.read_csv(file.csv, delimiter=",")
df = pd.DataFrame(["LONG GOOG VON", "Long Aapl X4 VON"], columns=["symbol"])
benchmarks = {"GOOG": "Google", "AAPL": "Apple"}
match = re.compile(r"\s(\S+)\s")
def f(value):
f1 = lambda x: benchmarks[match.findall(x)[0]] if match.findall(x)[0] in benchmarks else ""
stuff = f1(value)
#stuff done here is omitted
return stuff
df["full_name"] = df["symbol"].map(lambda x:f(x))
编译匹配时使用re.IGNORECASE
,然后将匹配结果转换为字典的大写。
import re
a = ["LONG GOOG VON", "Long Aapl X4 VON", 'no matches here']
match = re.compile(r"\s(\S+)\s", re.IGNORECASE)
benchmarks = {"GOOG": "Google", "AAPL": "Apple"}
for element in a:
s = match.search(element)
if s:
print(benchmarks.get(s.group(1).upper(), ''))
结果:
Google
Apple
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.