Create new columns in pandas from python nested lists

安稳与你 提交于 2019-12-23 15:44:11

问题


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

Example:

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

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

回答1:


You can try the following:

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



回答2:


pandas

Very similar to @Psidom's answer. However, I use pd.value_counts and will handle repeats

Use @Psidom's df

df = pd.DataFrame({'A': L})    

df.A.apply(pd.value_counts).fillna(0).astype(int)

numpy

More involved, but speedy

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)

Results

   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


来源:https://stackoverflow.com/questions/41916725/create-new-columns-in-pandas-from-python-nested-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!