3 回答

TA貢獻1155條經驗 獲得超0個贊
如果您有大型數(shù)據(jù)集,我會嘗試使用numpy.select
and?pandas.str.contains
:
import numpy as np
import pandas as pd
df["NewCol"] = np.select(
? ? condlist=[
? ? ? ? df["InvestmentDesc"].str.contains("1st lien|first lien", case=False, na=False),
? ? ? ? df["InvestmentDesc"].str.contains("2nd lien|second lien", case=False, na=False),
? ? ? ? df["InvestmentDesc"].str.contains("term loan", case=False, na=False),
? ? ],
? ? choicelist=[
? ? ? ? "1l", "2l", "tl"
? ? ],
? ? default=df["InvestmentDesc"]
)

TA貢獻1921條經驗 獲得超9個贊
您的應用函數(shù)存在語法問題。您不是將單個文本和字典作為參數(shù)傳遞,而是InvestmentDesc
在應用程序中傳遞整個系列 ( ) 列。因此,該函數(shù)在使用 的調用期間失敗lambda
。
必需的:
replace_all(dictReplace, text)
鑒于:
replace_all(dictRepStrings, df['InvestmentDesc'])
您可以自己解決這個問題,但為了可讀性,我建議您進行一些小的更改。嘗試將其與args
參數(shù)一起使用。
def replace_all(text, dictReplace): #Made dictReplace as second parameter
rep = dict((re.escape(k), v) for k, v in dictReplace.items())
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
return text
dictRepStrings = {"1st lien": "1l", "first lien": "1l", "2nd lien": "2l", "second lien": "2l", "term loan": "tl"}
df['NewCol'] = df['InvestmentDesc'].apply(replace_all, args=[dictRepStrings]) #modified apply function with args
df
請注意,我通過刪除更改了應用函數(shù)的結構lambda,添加了args參數(shù)并將其作為dict函數(shù)中的第二個參數(shù),因此apply將每一行作為dict第一個參數(shù)傳遞,第二個參數(shù)定義在args
這對我有用,如果您仍然遇到問題,請告訴我。

TA貢獻1811條經驗 獲得超6個贊
你也可以像這樣做一些相對簡單的事情:
def replacer(desc, replacers):
for key in replacers.keys():
if key in desc.lower():
desc = desc.lower().replace(key, replacers[key]).title()
return desc
replacers = {'1st lien': '1l', 'first lien': '1l', '2nd lien': '2l', 'second lien': '2l', 'term loan': 'tl'}
df['InvestmentDesc'].apply(replacer, replacers=replacers)
輸出:
0 Four Seasons 1L Tl
1 Arden Group 1L Tl
2 Four Seasons 1L Tl
3 Arden 1L Tl
不確定大寫是否重要,或者你可以稍微調整一下以獲得你想要的大寫。但我認為這是一個非常簡單的解決方案,并且還將考慮每個字符串中的多個匹配項
也許可以針對不區(qū)分大小寫的正則表達式搜索/替換修改它,但原理相同
添加回答
舉報