【问题标题】:String matching of two Pandas Series两个 Pandas Series 的字符串匹配
【发布时间】:2019-06-27 22:58:06
【问题描述】:

我在两个不同的数据帧中有两个(地址)列,每列具有不同的长度,我希望从数据帧的一列中迭代每个元素,而另一个数据帧的另一列。意思是,我希望检查第一个数据帧第一列中的每个元素是否与第二个数据帧第二列的任何元素匹配并返回一个布尔值。

如何在 python 中实现以上内容?

数据框 1:

0 New Delhi, India
1 Mumbai, India
2 Bangalore, India
3 Dwarka, New Delhi, India

数据框 2:

0 Nepal
1 Assam, India
2 Delhi

结果:(长度应等于 df 1 的 col 1 的 len)

True
False
False
True

【问题讨论】:

标签: python string pandas string-matching


【解决方案1】:
import pandas as pd
sales1 = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
     {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
     {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

sales2 = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
     {'account': 'A',  'Jan': 200, 'Feb': 210, 'Mar': 215},
     {'account': 'S',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

df1 = pd.DataFrame(sales1)
df2 = pd.DataFrame(sales2)

def CheckDF(df1,df2):
    for (item, Value),(item1, Value1) in 
    zip(df1['account'].iteritems(),df2['account'].iteritems()):
        if len(str(Value).strip()) == len(str(Value1).strip()):
            print(True)
        else:
            print(False)

CheckDF(df1,df2)

DF1:

   Feb  Jan  Mar    account
0  200  150  140  Jones LLC
1  210  200  215   Alpha Co
2   90   50   95   Blue Inc

DF2:

   Feb  Jan  Mar    account
0  200  150  140  Jones LLC
1  210  200  215          A
2   90   50   95          S

输出:

True
False
False

【讨论】:

  • 感谢苏拉杰的回答。但我正在寻找的不是两个不同字符串的长度匹配,而是字符串内容的匹配。如果 df1 和 df2 中的地址匹配,它应该相应地返回 True/False。
  • 基本上就是这样,只需要将if len(str(Value).strip()) == len(str(Value1).strip()):替换成if str(Value).strip() in str(Value1).strip():即可。看看其他人是否有矢量化解决方案很有趣。 +1
  • 我会试试这个,虽然我认为 'in' 比较行,即 df2 的行 [0] 中的 df1 的行 [0]。它不会与 df2 的所有行进行比较。
  • 我试过了,它不能正常工作。我使用了与 Suraj 说明的相同的示例,只是将“Jones LLC”从一个数据框中的第一个位置更改为最后一个位置,它无法识别它的存在。
猜你喜欢
  • 2019-02-25
  • 2019-12-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多