[英]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.