【问题标题】:Creating new DataFrame from the cartesian product of 2 lists从 2 个列表的笛卡尔积创建新的 DataFrame
【发布时间】:2023-03-10 11:50:01
【问题描述】:

我想要在 Pandas 中实现以下目标:

a = [1,2,3,4]
b = ['a', 'b']

我可以创建一个像这样的 DataFrame:

column1 column2
'a'        1
'a'        2
'a'        3
'a'        4
'b'        1
'b'        2
'b'        3
'b'        4

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    itertools.productDataFrame 构造函数一起使用:

    a = [1, 2, 3, 4]
    b = ['a', 'b']
    
    from itertools import product
    
    # pandas 0.24.0+
    df = pd.DataFrame(product(b, a), columns=['column1', 'column2'])
    # pandas below 
    # df = pd.DataFrame(list(product(b, a)), columns=['column1', 'column2'])
    print (df)
      column1  column2
    0       a        1
    1       a        2
    2       a        3
    3       a        4
    4       b        1
    5       b        2
    6       b        3
    7       b        4
    

    【讨论】:

      【解决方案2】:

      我会在这里提出另一种方法,以防万一有人喜欢它。

      下面的完整模型:

      import pandas as pd 
      a = [1,2,3,4] 
      b = ['a', 'b']
      df=pd.DataFrame([(y, x) for x in a for y in b], columns=['column1','column2'])
      df
      

      结果如下:

          column1 column2
      0   a   1
      1   b   1
      2   a   2
      3   b   2
      4   a   3
      5   b   3
      6   a   4
      7   b   4
      

      【讨论】:

        猜你喜欢
        • 2021-10-22
        • 2020-09-12
        • 2011-05-06
        • 2012-01-03
        • 2012-02-25
        • 2022-01-06
        • 2012-03-24
        • 1970-01-01
        相关资源
        最近更新 更多