[英]Partial String Matching in Pandas Dataframe
我有一個 dataframe 包含一個字符串列,其中包含幾個不同的 4 個字符,可以用|
分隔或&
,但並非總是如此。 我正在嘗試為每個離散的 4 個字符項目 map 一個字典,但遇到了問題。 pandas 版本 23.4
我嘗試使用的基本代碼:
df = df.replace(dict, regex=True)
或者如果嘗試 select 一個特定的列:
df['Col'] = df['Col'].replace(dict, regex=True)
兩者都引發以下錯誤:
ValueError: The truth value of an array with more that one element is ambiguous. Use a.any() or a.all()
字典的值是類型list
。 這會是執行.replace
的問題嗎?
使用示例 df 和 dict 更新
ID Code
ABCD 00FQ
JKFA 8LK9|4F5H
QWST 2RLA|R1T5&8LK9
dict={'00FQ':['A','B'], '8LK9':['X'], '4F5H':['U','Z'], '2RLA':['H','K'], 'R1T5':['B','G'] }
字典中的元素將比 dataframe 中的元素更多。
使用預期的 output 更新
ID Code Logic
ABCD 00FQ ['A','B']
JKFA 8LK9|4F5H ['X'] | ['U','Z']
QWST 2RLA|R1T5&8LK9 ['H','K'] | ['B','G'] & ['X']
總體目標是在兩個數據幀上執行此替換,然后比較兩側的ID's
是否相等。
dict 中定義的正則表達式可能與 dataframe 的多行匹配,並且 python 對從 dict 中獲取哪個替換值感到困惑。
並且,當檢查 numpy 數組的 boolean 值時,此錯誤被迫避免用戶猜測。 如果你認為一個元素數組是 True
因此它會拋出此錯誤以允許程序員明確提及它。
Go 在這里進行更多說明。
這是一個 function 它將允許您從字符串中解析相關值:
def string_to_list(string):
"""
parses a parent string for 4 character children strings
returns a list of children strings
"""
# instantiate values
child = ''
children = []
if len(string)<4:
return None
for n in string:
# skip if not wanted
if n in ['|','&']:
continue
child+=n
if len(child)==4:
children.append(child)
child = ''
# finished
return children
應用它來提取值列表,如下所示:
df['Code_List'] = df['Code'].apply(string_to_list)
Map 到相關logic
值:
# Instantiate the dictionary of logic rules
logic_dict = {'00FQ':['A','B'], '8LK9':['X'], '4F5H':['U','Z'], '2RLA':['H','K'], 'R1T5':['B','G'] }
# Map the logic rules
df['Logic_List'] = df['Code_List'].apply(lambda arr: [logic_dict[x] for x in arr])
# Final output
ID Code Code_List Logic_List
0 ABCD 00FQ [00FQ] [[A, B]]
1 JKFA 8LK9|4F5H [8LK9, 4F5H] [[X], [U, Z]]
2 QWST 2RLA|R1T5&8LK9 [2RLA, R1T5, 8LK9] [[H, K], [B, G], [X]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.