Skip to main content
 首页 » 编程设计

python之Pandas map lambda 函数的不区分大小写的字典

2025年05月04日25dyllove98

下面,我在函数中使用 lambda x: 将值map 到 pandas 列(如果它们出现在字典中)基准。

在示例中,符号 “GOOG” 被映射为 “Google” 到列 “full_name”。

我的问题是:如何对字典进行不区分大小写的检查?因此,例如,"Aapl" 变成了 "Apple",即使 "AAPL" 在字典中也是如此。

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