地址匹配两列python

时间:2019-02-06 11:28:09

标签: python regex python-3.x string-matching

考虑我在数据框中有两列:

第1列:

第1行:堆栈溢出

第2行:Python

第2列:

第1行:['Stack','Stack Overflow']

第2行:['Python编程','Python Snake']

我想逐行进行精确匹配(可选),并相应地返回一个标志。

输出:

[0]匹配

[1]不匹配

尝试过: 我已经尝试过在循环中使用“输入”功能,但这也可以部分匹配“匹配”。

代码:

for (item, Value),(item1, Value1) in zip(df1['Column1'].iteritems(),df2['Column2'].iteritems()):

    if str(Value).strip() in str(Value1).strip():
       found.append(1)

2 个答案:

答案 0 :(得分:0)

我认为您需要:

def isMatch(row):
    for i in row['b']:
        if i == row['a']:
            return 'Match'
    return 'Not Match'

df['c'] = df.apply(lambda x: isMatch(x), axis=1)
print(df)

答案 1 :(得分:0)

好的,我会尝试回答这个问题,所以如果其他人也有类似的问题。基本上,您正在寻找col1值是否在col2(列表)中。您可以轻松使用isin。 应用numpy where函数,可以创建一个标志。

这是一个样机。

df = pd.DataFrame({
    'col1': ['Stack Overflow', 'Python'], 
    'col2': [ ['Stack', 'Stack Overflow'],  ['Python Programming', 'Python Snake']]})


df['Flag'] =df.apply(lambda x: x['col1'] in x['col2'], axis=1)
df

结果如下:

    col1    col2    Flag
0   Stack Overflow  [Stack, Stack Overflow] True
1   Python  [Python Programming, Python Snake]  False

让我知道它是否有效。

相关问题