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