【问题标题】:I getting an empty lists after intersect in python在 python 中相交后我得到一个空列表
【发布时间】:2021-11-19 09:36:20
【问题描述】:

我有 2 列,每列每行有 5 个单词。

例如:
x=[狗|猫|鼠标|新|世界]
y=[fish|cat|new|thing|nice]

我需要找到它们之间的交叉点 [cat|new]。

但它显示了一个空列表。你知道为什么吗?

data = pd.read_csv('data.csv')

intersect1=[]
    
for j in range(len(data)):
    #print('==========================================================================')
        x=str(data.iloc[:, 2]).split("|")
        y=str(data.iloc[:, 3]).split("|")  


        #get_jaccard_sim(x, y) 
    
        #intersect.append(result)


        intersect= list(set(x) & set(y))   
        intersect1.append(intersect)
    
#print(inter)
print(intersect1)

【问题讨论】:

    标签: python pandas list numpy intersect


    【解决方案1】:

    问题出在您的迭代循环中,当您只想逐行选择每个值时,您在执行data.iloc[:,2] 时选择了整列。更改 : 以在循环中使用计数器 j

    df = pd.DataFrame({'x': ['dog|cat|mouse|new|world'],
                       'y': ['fish|cat|new|thing|nice']})
      
    for j in range(len(df)):
          x=str(df.iloc[j, 0]).split("|")
          y=str(df.iloc[j, 1]).split("|")
          intersect= list(set(x) & set(y))   
    
    print(intersect)
    

    输出:

    ['new', 'cat']
    

    【讨论】:

    • 这样我也得到了空列表
    • 您需要分享一个更具体的数据集供我们研究。上面的代码对我来说效果很好
    • 我意识到我在 excel 中选择了错误的列,这就是原因。谢谢!
    【解决方案2】:

    即使您在循环中添加了代码,您实际上并没有遍历您的数据框。假设您的数据是这种形状:

        one two
    0   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    1   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    2   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    3   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    4   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    5   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    6   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    7   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    8   [dog|cat|mouse|new|world]   [fish|cat|new|thing|nice]
    ...
    

    然后假设您感兴趣的列是 2 和 3,像这样修改您的工作:

    for j in range(len(data)):
        x = data.iloc[j, 2][0].split('|')
        y = data.iloc[j, 3][0].split('|')
        intersect = list(set(x) & set(y))
    

    【讨论】:

      【解决方案3】:

      我刚刚用下面的代码做了一个测试:

      data1 = "dog|cat|mouse|new|world"
      data2 = "fish|cat|new|thing|nice"
      
      x = data1.split("|")
      y = data2.split("|")
      
      intersect= list(set(x) & set(y))
      
      print(intersect)
      

      这会输出 ['cat', 'new'],这正是您所期望的。请注意,xy 是包含单词作为单独字符串的数组,

      ['dog', 'cat', 'mouse', 'new', 'world'] # this is x
      ['fish', 'cat', 'new', 'thing', 'nice'] # this is y
      

      确保您的代码也是如此!

      【讨论】:

        猜你喜欢
        • 2021-09-07
        • 2023-01-01
        • 2021-09-08
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 2018-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多