简体   繁体   English

将元素中的列表转换为字典或替换Python中pandas数据框中元素中的特殊字符

[英]Convert list to dictionary in element Or replace special characters in element in data frame of pandas in Python

I'm working on a dataframe like this in pandas:我正在熊猫中处理这样的数据框:

item_type  item_price  item_env                                        item_detail
sofa          2880     [natural wood, eco-friendly]                 [2pax,seglora]     
sofa          2400     [solid wood, recycle, reuse]                 [3pax,knisa]
chair         1200      nan                                               [Red]
desk          2000      nan                                              [blue]

And I want to change to result like this:我想改变成这样的结果:

item_type  item_price  item_env                                        item_detail
sofa          2880     {natural wood, eco-friendly}                 {2pax,seglora}  
sofa          2400     {solid wood, recycle, reuse}                 {3pax,knisa}
chair         1200      nan                                               {Red}
desk          2000      nan                                              {blue}

I try to use replace and str.replace and some other method but it fail.我尝试使用replacestr.replace以及其他一些方法,但它失败了。 So, I wanna ask how can do to get the expected result?所以,我想问一下怎么做才能得到预期的结果?

You need to escape the meta character of regular expressions, passing regex as True , whether you are using DataFrame.replace or Series.str.replace .您需要转义正则表达式的元字符,将regex作为True传递,无论您使用的是DataFrame.replace还是Series.str.replace

>>> df[['item_env', 'item_detail']] = (df[['item_env', 'item_detail']]
                                        .replace('\[', '{', regex=True)
                                        .replace('\]', '}', regex=True)
                                       )

OUTPUT:输出:


  item_type  item_price                      item_env     item_detail
0      sofa        2880  {natural wood, eco-friendly}  {2pax,seglora}
1      sofa        2400  {solid wood, recycle, reuse}    {3pax,knisa}
2     chair        1200                           NaN           {Red}
3      desk        2000                           NaN          {blue}

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

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