【问题标题】:Convert list to dictionary in element Or replace special characters in element in data frame of pandas in Python将列表转换为元素中的字典或在Python中替换熊猫数据框中元素中的特殊字符
【发布时间】:2021-09-21 07:27:41
【问题描述】:

我正在 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]

我想改变成这样的结果:

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}

我尝试使用replacestr.replace 以及其他一些方法,但它失败了。那么,我想问一下如何才能得到预期的结果?

【问题讨论】:

  • print(df.loc[0,'item_env'])print(df.loc[0,'item_detail']) 的输出是什么?
  • 在标题中您提到了 dicts,但您当前正在所需输出中显示集合(例如 {natural wood, eco-friendly})。你需要什么?
  • 其实这个dataframe是从json文件和print(df)转换而来的。在第一个 dataframe 中,元素是 ``` [natural wood, eco-friendly] ``` 我想改成 ``` {natural wood, eco-friendly} ```

标签: python pandas list dataframe dictionary


【解决方案1】:

您需要转义正则表达式的元字符,将regex 传递为True,无论您使用的是DataFrame.replace 还是Series.str.replace

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

输出:


  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}

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多