从python嵌套列表在pandas中创建新列 [英] Create new columns in pandas from python nested lists

查看:492
本文介绍了从python嵌套列表在pandas中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框.列之一具有嵌套列表.我想从嵌套列表中创建新列

I have a pandas data frame. One of the columns has a nested list. I would like to create new columns from the nested list

示例:

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

我希望嵌套列表中的所有元素都作为列.如果列表包含元素,则值应为1,否则为0.

I want all the elements in the nested lists as columns. The value should be one if the list has the element and zero if it does not.

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嵌套列表在pandas中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆