python – 迭代pandas数据帧中的所有列以拆分分隔符
发布时间:2020-12-20 11:05:27 所属栏目:Python 来源:网络整理
导读:我有一个如下所示的数据框: name val0 cat ['Furry: yes','Fast: yes','Slimy: no','Living: yes']1 dog ['Furry: yes','Living: yes']2 snail ['Furry: no','Fast: no','Slimy: yes','Living: yes']3 paper ['Furry: no','Living: no'] 对于val列中列表中
我有一个如下所示的数据框:
name val 0 cat ['Furry: yes','Fast: yes','Slimy: no','Living: yes'] 1 dog ['Furry: yes','Living: yes'] 2 snail ['Furry: no','Fast: no','Slimy: yes','Living: yes'] 3 paper ['Furry: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |