繁体   English   中英

根据 python 中的映射字典将列表列转换为多列

[英]convert a list column to multiple columns based on a mapping dictionary in python

假设我有一个 pandas dataframe 列,其中包含一个列表:

d = {'id': ["First", "Second"], 'list_column': [[1,2,3], [3,2]]}
pd.DataFrame(data=d)

看起来像这样:

| id       | list_column |
| -------- | ----------- |
| First    | [1, 2, 3]   |
| Second   | [3, 2]      |

我还有一个字典,将列表值映射到一个键,例如:

dict = {
  1: "red",
  2: "blue",
  3: "green"
}

如何将我的 list_column 转换为反映列表列内容的多个列,例如:

| id       | red | blue | green |
| -------- | --- | ---- | ----- |
| First    | 1   | 1    | 1     |
| Second   | 0   | 1    | 1     |

您可以先分解列,然后使用字典 map 值,然后使用pandas.crossTab创建所需的结果:

# df is your dataframe, and dict_ is your dict with key,value pairs
>>> temp=df.explode('list_column')
>>> out = pd.crosstab(temp['id'], temp['list_column'].map(dict_))

OUTPUT

# out

list_column  blue  green  red
id                           
First           1      1    1
Second          1      1    0

@Mozway 在评论中建议的优化版本:

>>> temp=df.explode('list_column')
>>> out=pd.crosstab(temp['id'], temp['list_column']).rename(columns=dict_)

# out
list_column  red  blue  green
id                           
First          1     1      1
Second         0     1      1

它经过优化,因为它不需要在行级别 map,而只是在最终计算后重命名列,这比第一种方法确实有效。

代码:

df['list_column'] = df.apply(lambda x: [dic.get(e, e) for e in x.list_column],axis=1)
df.explode('list_column').pivot_table(index=['id'], columns='list_column', aggfunc='size', fill_value=0)

Output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM