【问题标题】:How to get all unique combinations of values in one column that are in another column如何获取一列中另一列中的所有唯一值组合
【发布时间】:2021-12-30 21:02:25
【问题描述】:

从这样的数据框开始:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'b', 'b', 'a']})
   A  B
0  1  a
1  2  b
2  3  b
3  4  b
4  5  a

获取这样的数据框的最佳方法是什么?

pd.DataFrame({'source': [1, 2, 2, 3], 'target': [5, 3, 4, 4]})
   source  target
0       1       5
1       2       3
2       2       4
3       3       4

每当 A 列中的一行在 B 列中与 A 列中的另一行具有相同的值时,我想将该关系的唯一实例保存在新的数据框中。

这很接近:

df.groupby('B')['A'].unique()
B
a       [1, 5]
b    [2, 3, 4]
Name: A, dtype: object

但我现在最好将其转换为单个数据帧,而我的大脑已经瘫痪了。

【问题讨论】:

    标签: python pandas combinations relationship


    【解决方案1】:

    在你的情况下,你可以做itertools.combinations

    import itertools
    s = df.groupby('B')['A'].apply(lambda x : set(list(itertools.combinations(x, 2)))).explode().tolist()
    out = pd.DataFrame(s,columns=['source','target'])
    out
    Out[312]: 
       source  target
    0       1       5
    1       3       4
    2       2       3
    3       2       4
    

    【讨论】:

      【解决方案2】:

      使用合并功能

      df.merge(df, how = "outer", on = ["B"]).query("A_x < A_y")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-17
        • 2018-08-05
        • 2021-10-17
        • 1970-01-01
        • 2012-10-06
        • 2021-07-22
        • 2020-10-09
        • 1970-01-01
        相关资源
        最近更新 更多