[英]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.我尝试使用replace
和str.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.