【问题标题】:Pandas - Finding the intersection of values in two dataframes, return a single dataframe of same size with number of intersectionsPandas - 查找两个数据框中的值的交集,返回具有相同大小的单个数据框和交集的数量
【发布时间】:2020-10-09 16:34:22
【问题描述】:

我正在寻找一种方法来返回一个 (n x n) 数据帧,其中数据帧的每个值都是两个数据帧的值之间的交集数(两者的大小都是 n x n)。

我不太确定如何在两个数据帧之间进行这样的操作。非常感谢任何帮助。

谢谢!

df1
              0             1
0  [4, 7, 3, 5]  [4, 7, 3, 5]
1     [8, 2, 6]     [8, 2, 6]
2  [9, 1, 8, 2]  [9, 1, 8, 2]
3        [3, 5]        [3, 5]
4     [9, 4, 8]     [9, 4, 8]
5     [0, 1, 4]     [0, 1, 4]

df2
              0             1
0  [2, 3, 6, 9]  [6, 2, 3, 5]
1  [2, 3, 6, 9]  [6, 2, 3, 5]
2  [2, 3, 6, 9]  [6, 2, 3, 5]
3  [2, 3, 6, 9]  [6, 2, 3, 5]
4  [2, 3, 6, 9]  [6, 2, 3, 5]
5  [2, 3, 6, 9]  [6, 2, 3, 5]

df3 - intended dataframe to be returned
              0             1
0             1             2
1             1             2
2             2             1
3             1             2
4             0             0
5             0             0

编辑:修正了示例结果的错误

【问题讨论】:

    标签: python pandas dataframe intersection


    【解决方案1】:

    嗯,我无法直接对 pandas 执行此操作,我只有 dicts 的解决方案。而且我认为您的示例结果有误,我认为我的结果是预期的结果。

    import pandas as pd
    
    # Prework to get your data
    data = {0: [[4, 7, 3, 5], [8, 2, 6], [9, 1, 8, 2], [3, 5], [9, 4, 8], [0, 1, 4]],
            1: [[4, 7, 3, 5], [8, 2, 6], [9, 1, 8, 2], [3, 5], [9, 4, 8], [0, 1, 4]]}
    
    data2 = {0: [[2, 3, 6, 9], [2, 3, 6, 9], [2, 3, 6, 9], [2, 3, 6, 9], [2, 3, 6, 9], [2, 3, 6, 9]],
             1: [[6, 2, 3, 5], [6, 2, 3, 5], [6, 2, 3, 5], [6, 2, 3, 5], [6, 2, 3, 5], [6, 2, 3, 5]]}
    
    df = pd.DataFrame(data)
    df2 = pd.DataFrame(data2)
    
    # ---
    
    dc = df.to_dict()
    dc2 = df2.to_dict()
    
    new_dc = dc.copy()
    for key in dc:
        for val in dc[key]:
            new_dc[key][val] = len(set(dc[key][val]).intersection(dc2[key][val]))
    new_df = pd.DataFrame(new_dc)
    
    print(new_df)
    

    输出:

       0  1
    0  1  2
    1  2  2
    2  2  1
    3  1  2
    4  1  0
    5  0  0
    

    【讨论】:

    • 非常感谢您的时间和前期工作。我不知道字典的力量以及它们在解决这些问题中的用途。非常感激。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2017-08-25
    • 1970-01-01
    相关资源
    最近更新 更多