【问题标题】:Address Matching two columns python地址匹配两列python
【发布时间】:2019-06-30 08:16:47
【问题描述】:

假设我在数据框中有两列:

第 1 列:

第 1 行:堆栈溢出

第 2 行:Python

第 2 栏:

第 1 行:['堆栈','堆栈溢出']

第 2 行:['Python Programming', 'Python Snake']

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

输出:

[0] 匹配

[1] 不匹配

试过了: 我在循环中尝试了“in”函数,但这也将部分匹配作为“匹配”。

代码:

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

    if str(Value).strip() in str(Value1).strip():
       found.append(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)
  • @DeepankarGarg 编辑您的问题并添加代码...不要在 cmets 中发布
  • 谢谢,我们到了。如果您可以创建一个突出显示问题的示例数据框 df,然后输入您尝试过的代码,这将非常有帮助。

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


【解决方案1】:

好的,我会尝试回答这个问题,所以如果其他人有类似的问题。基本上,您要检查col1 值是否在col2(列表)中。您可以轻松使用isin。 应用numpywhere函数,就可以创建flag了。

这是一个模型。

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

让我知道它是否有效。

【讨论】:

    【解决方案2】:

    我认为你需要:

    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)
    

    【讨论】:

    • 不,这对我不起作用。您是否尝试过我提供的相同数据集?格式一样吗?
    • 它返回所有“不匹配”给我。我的一些记录确实匹配。
    • 我认为我的第二列不是包含字符串的列表,这就是它可能无法匹配的原因。
    • "['rampuri, kalkaji', 'tughlakabad extension, tughlakabad', 'govindpuri rd, govindpuri', 'govindpuri', 'giri nagar, kalkaji']"
    • 以上是我第二列的其中一行。
    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多