【问题标题】:Explode data in Python [closed]在 Python 中展开数据 [关闭]
【发布时间】:2022-11-11 16:07:30
【问题描述】:

我的表中有我想分解的数据

输入:

| Col 1    | Col 2    | Col 3   |
| -------- | ---------|---------|
| [A,B,C,D]| Value 1  | Value 2 |

预期输出:“col 1”在 [A,B,C,D] 组合中展开。 值“col 1”的长度可以变化,这些值也是动态的

| Col 1    | Col 2    | Col 3 |
| -------- | -------- |-------|
| [A,B]    | Value 1  |Value 2|
| [A,C]    | Value 1  |Value 2|
| [A,D]    | Value 1  |Value 2|
| [B,C]    | Value 1  |Value 2|
| [B,D]    | Value 1  |Value 2|
| [C,D]    | Value 1  |Value 2|

【问题讨论】:

    标签: python pandas pandas-explode


    【解决方案1】:

    让我们在Col 1 列上使用itertools.combinations 然后爆炸

    import itertools
    
    df['Col 1'] = df['Col 1'].apply(lambda lst: list(itertools.combinations(lst, 2)))
    out = df.explode('Col 1', ignore_index=True)
    
    print(out)
    
        Col 1    Col 2    Col 3
    0  (A, B)  Value 1  Value 2
    1  (A, C)  Value 1  Value 2
    2  (A, D)  Value 1  Value 2
    3  (B, C)  Value 1  Value 2
    4  (B, D)  Value 1  Value 2
    5  (C, D)  Value 1  Value 2
    

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 2023-03-20
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      相关资源
      最近更新 更多