【发布时间】:2014-05-07 08:43:47
【问题描述】:
我有一个带有可变逗号分隔文本的数据框列,只是试图提取基于另一个列表找到的值。所以我的数据框看起来像这样:
col1 | col2
-----------
x | a,b
listformatch = [c,d,f,b]
pattern = '|'.join(listformatch)
def test_for_pattern(x):
if re.search(pattern, x):
return pattern
else:
return x
#also can use col2.str.contains(pattern) for same results
上面的过滤效果很好,但不是在找到匹配项时返回b,而是返回整个模式,例如a|b,而不仅仅是b,而我想用它找到的模式创建另一列,例如b。
这是我的最终函数,但仍然得到 UserWarning: This pattern has match groups. To actually get the groups, use str.extract." groups, use str.extract.", UserWarning) 我希望我能解决:
def matching_func(file1, file2):
file1 = pd.read_csv(fin)
file2 = pd.read_excel(fin1, 0, skiprows=1)
pattern = '|'.join(file1[col1].tolist())
file2['new_col'] = file2[col1].map(lambda x: re.search(pattern, x).group()\
if re.search(pattern, x) else None)
我想我现在了解 pandas extract 的工作原理,但在正则表达式上可能仍然生疏。如何创建用于以下示例的模式变量:
df[col1].str.extract('(word1|word2)')
我想创建变量为pattern = 'word1|word2',而不是在参数中包含单词,但由于创建字符串的方式,这将不起作用。
我在 pandas 0.13 中使用矢量化字符串方法的最终和首选版本:
使用一列中的值从第二列中提取:
df[col1].str.extract('({})'.format('|'.join(df[col2]))
【问题讨论】:
-
改用
re.search(pattern, x).group(0)