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

例子:

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

最佳答案

您可以尝试以下操作:

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

关于python - 从python嵌套列表在pandas中创建新列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41916725/

10-11 22:48
查看更多