【问题标题】:How to find out if two strings in two different Pandas dataframes are equal?如何找出两个不同 Pandas 数据框中的两个字符串是否相等?
【发布时间】:2021-03-24 11:59:23
【问题描述】:

我有两个不同的数据框,A 和 B,它们有一个列,每个列都有一个字符串。我的目标是遍历 A 中的字符串列并检查 B 中是否存在该字符串,如果不存在,则对 A 中的其他列进行一些计算,然后使用 A 中的值向 B 写入一个新行。我很难检查字符串相似度。

我试过这个:

if A.string1.isin(B.string2.any() : 

我得到一个 TypeError: only list-like objects are allowed to be passed to isin(), you pass a [str]

我也尝试过在 A 上使用 for 循环:

for value in A.itertuples() :
  if value.string1.isin(B.string2.any()) :

然后我得到 AttributeError: 'str' object has no attribute 'isin'

样本数据:

A = pd.DataFrame({'A': ["john doe", " john doe", 'John'], 'B': [6, 7, 8]})
B = pd.DataFrame({'C': ["john dow", " john dough", 'john doe'], 'D': [9, 10, 11]})

有什么想法吗?

【问题讨论】:

  • 能否提供一个示例数据
  • 当然! A = pd.DataFrame({'A': ["john doe", " john doe", 'John'], 'B': [6, 7, 8]})B = pd.DataFrame({'C': ["john dow", " john dough", 'John doe'], 'D': [9, 10, 11]})

标签: python pandas string for-loop isin


【解决方案1】:

你试过了吗:Source

A.string1.isin(B.string2)

对于您收到的所有 False,您可以相应地修改您的代码。

【讨论】:

  • 我试过这个,但我得到 AttributeError 'str' object has no attribute 'isin'。有什么想法吗?
【解决方案2】:
import pandas as pd 

di1 = {"A":["a","b","c","d"],"B":["a","b","c","d"]}

di2 = {"A":["a","45","c","d"],"B":["a","b","c","d"]}

data1 = pd.DataFrame(di1) #first dataframe
data2 = pd.DataFrame(di2) #second dataframe

for value in list(data1.A):
  if value in list(data2.A) :
      print(value) # print only if values are common in two dataframes

【讨论】:

  • 谢谢,这行得通。问题是在 for 循环中我需要对 A 中的其他列进行计算。当我只遍历一列中的值列表中的值时,我无法检索其他列中的相应值以执行这些计算.
【解决方案3】:

我找到了解决办法!

for value in A.itertuples() :
  if value.A in list(B.C) :
    do calculations on other columns in A

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 2015-10-30
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    相关资源
    最近更新 更多