【问题标题】:Create new columns in pandas from python nested lists从 python 嵌套列表在 pandas 中创建新列
【发布时间】:2017-06-14 11:28:25
【问题描述】:

我有一个熊猫数据框。其中一列有一个嵌套列表。我想从嵌套列表中创建新列

例子:

L = [[1,2,4],
    [5,6,7,8],
    [9,3,5]]

我希望嵌套列表中的所有元素都作为列。如果列表有元素,则该值应为 1,如果没有,则该值应为 0。

1 2 4 5 6 7 8 9 3
1 1 1 0 0 0 0 0 0
0 0 0 1 1 1 1 0 0
0 0 0 1 0 0 0 1 1

【问题讨论】:

    标签: python pandas numpy reshape


    【解决方案1】:

    pandas

    与@Psidom 的回答非常相似。但是,我使用 pd.value_counts 并会处理重复

    使用@Psidom 的df

    df = pd.DataFrame({'A': L})    
    
    df.A.apply(pd.value_counts).fillna(0).astype(int)
    

    numpy

    更多参与,但速度更快

    lst = df.A.values.tolist()
    n = len(lst)
    lengths = [len(sub) for sub in lst]
    flat = np.concatenate(lst)
    u, inv = np.unique(flat, return_inverse=True)
    rng = np.arange(n)
    slc = np.hstack([
            rng.repeat(lengths)[:, None],
            inv[:, None]
        ])
    data = np.zeros((n, u.shape[0]), dtype=np.uint8)
    data[slc[:, 0], slc[:, 1]] = 1
    pd.DataFrame(data, df.index, u)
    

    结果

       1  2  3  4  5  6  7  8  9
    0  1  1  0  1  0  0  0  0  0
    1  0  0  0  0  1  1  1  1  0
    2  0  0  1  0  1  0  0  0  1
    

    【讨论】:

      【解决方案2】:

      您可以尝试以下方法:

      df = pd.DataFrame({"A": L})
      
      df
      #          A
      #0  [1, 2, 4]
      #1  [5, 6, 7, 8]
      #2  [9, 3, 5]
      
      # for each cell, use `pd.Series(1, x)` to create a Series object with the elements in the 
      # list as the index which will become the column headers in the result
      df.A.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)
      
      #   1   2   3   4   5   6   7   8   9
      #0  1   1   0   1   0   0   0   0   0
      #1  0   0   0   0   1   1   1   1   0
      #2  0   0   1   0   1   0   0   0   1
      

      【讨论】:

      • pd.Series(1, x) - 这很聪明!
      • 太棒了。正是我想要的!
      • @MaxU,完成!我是新来的。谢谢你告诉我。
      • @fuzzyhedge,由于我提到我在 pandas df 的其中一列中有嵌套列表,MaxU 通过将嵌套列表 L 转换为 pandas df 列来开始解决方案。希望我回答了你的问题。
      • @Prasanth 你现在也有代表支持这个答案了
      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多