第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

替換數(shù)據(jù)框列中的多個字符串的函數(shù) - “TypeError:預期的字符串或類似字節(jié)的對象”

替換數(shù)據(jù)框列中的多個字符串的函數(shù) - “TypeError:預期的字符串或類似字節(jié)的對象”

喵喵時光機 2023-06-20 13:25:50
我有以下形式的大型數(shù)據(jù)框:FundManager | AsOfDate | InvestmentDesc | Amount  ManagerA | 6/1/2020 | Four Seasons 1st lien TL | 25500.86  ManagerA | 6/1/2020 | Arden Group First Lien TL | 28731.00  ManagerB | 6/1/2020 | Four Seasons 1L Term Loan | 16853.00  ManagerB | 6/1/2020 | Arden 1st Lien Term Loan | 50254.30相同的基礎金融工具通常由多個資產管理人持有,但描述方式略有不同,如上表所示(例如“四季 1st 留置權 TL”與“四季 1L 定期貸款”)。我正在嘗試找出對 pandas 數(shù)據(jù)框中的“InvestmentDesc”列進行某些替換的最佳方法(例如,將“Term Loan”替換為“TL”,將“1st Lien”替換為“1L”),理想情況下(i)以一種不必為每個術語重復遍歷數(shù)百萬行的方式,以及 (ii) 可以在數(shù)據(jù)框中的少數(shù)其他列上使用但使用單獨的術語列表進行替換的方式。我目前有以下功能:def replace_all(dictReplace, text):    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然后我試圖將要替換的術語列表傳遞到其中(我假設是字典?)和要修改的現(xiàn)有數(shù)據(jù)框列:dictRepStrings = {"1st lien": "1l", "first lien": "1l", "2nd lien": "2l", "second lien": "2l", "term loan": "tl"}df['NewCol'] = df['InvestmentDesc'].apply(lambda x: replace_all(dictRepStrings, df['InvestmentDesc']))df然而,在這樣做時,我最終得到“TypeError: expected string or bytes-like object”,如下所示:---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-10-a37630bdc5a4> in <module>     23      24 dictRepStrings = {"1st lien": "1l", "first lien": "1l", "2nd lien": "2l", "second lien": "2l", "term loan": "tl"}---> 25 df['NewCol'] = df['InvestmentDesc'].apply(lambda x: replace_all(dictRepStrings, df['InvestmentDesc']))     26 df~\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)   3846             else:   3847                 values = self.astype(object).values-> 3848                 mapped = lib.map_infer(values, f, convert=convert_dtype)   3849    3850         if len(mapped) and isinstance(mapped[0], Series):經過兩天的谷歌搜索直到沮喪,我根本無法弄清楚我做錯了什么或如何解決。任何關于我應該如何進行的建議或想法將不勝感激!
查看完整描述

3 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

如果您有大型數(shù)據(jù)集,我會嘗試使用numpy.selectand?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"]

)


查看完整回答
反對 回復 2023-06-20
?
郎朗坤

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


這對我有用,如果您仍然遇到問題,請告訴我。


查看完整回答
反對 回復 2023-06-20
?
楊魅力

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ū)分大小寫的正則表達式搜索/替換修改它,但原理相同


查看完整回答
反對 回復 2023-06-20
  • 3 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號