python - 遍历 pandas 数据框中的所有列以按分隔符拆分

标签 python list pandas dataframe split

我有一个如下所示的数据框:

    name   val
0   cat    ['Furry: yes', 'Fast: yes', 'Slimy: no', 'Living: yes']
1   dog    ['Furry: yes', 'Fast: yes', 'Slimy: no', 'Living: yes']
2   snail  ['Furry: no', 'Fast: no', 'Slimy: yes', 'Living: yes']
3   paper  ['Furry: no', 'Fast: no', 'Slimy: no', 'Living: no']

对于 val 列中列表中的每个项目,我想在“:”分隔符上拆分项目。然后我想让 item[0] 成为列名,而 item[1] 成为该特定列的值。像这样:

    name   Furry  Fast  Slimy  Living
0   cat    yes    yes   no     yes
1   dog    yes    yes   no     yes
2   snail  no     no    yes    yes
3   paper  no     no    no     no

我已经尝试将 apply(pd.Series) 应用于 val 列,但这仍然给我留下许多列,我必须手动进行拆分,或者弄清楚如何迭代遍历所有列并做劈叉。我更喜欢从零开始拆分并创建列名。知道如何实现这一点吗?

最佳答案

pd.DataFrame 直接接受字典列表。因此,您可以通过列表理解构建数据框,然后加入。

L = [dict(i.split(': ') for i in x) for x in df['val']]

df = df[['name']].join(pd.DataFrame(L))

print(df)

    name Fast Furry Living Slimy
0    cat  yes   yes    yes    no
1    dog  yes   yes    yes    no
2  snail   no    no    yes   yes
3  paper   no    no     no    no

关于python - 遍历 pandas 数据框中的所有列以按分隔符拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50751177/

相关文章:

python - 如何使用tensorflow在全连接层中恢复

c# - 内存不足异常

list - 合并序言中的列表列表

python - 有没有更简单的方法来使 pandas.Series 单调?

python - 在 VPN 设置中信任 request.remote_addr 是否安全

python - 如何使用 to_dict() 创建一个键、值对均为整数的字典?

Python 类列表问题

python - 更好的方法去堆叠 Pandas 行?

python - Pandas - map 函数的错误行为

python 和 Pandas : display all rows without omitting