我以以下数据帧为例:
test = pd.DataFrame({'type':['fruit-of the-loom (sometimes-never)', 'yes', 'ok (not-possible) I will try', 'vegetable', 'poultry', 'poultry'],
'item':['apple', 'orange', 'spinach', 'potato', 'chicken', 'turkey']})
我发现很多人想从字符串或类似情况中删除括号,但在我的例子中,我希望保留字符串的原样,除了我想删除字符串括号内的hyphen
有人对我如何做到这一点有什么建议吗
str.split()
将处理前导的连字符,而str.rsplit()
将处理尾随的连字符。我想不出一个办法来解决这个问题
在这种情况下,此假设列中值的理想结果为:
'fruit-of the-loom (sometimes never)',
'yes',
'ok (not possible) I will try',
'vegetable',
'poultry',
'poultry'`
我应该多花点时间考虑这个问题
这就是我想出的解决办法”
计数括号,替换正确计数范围内的内容
完成后,将其应用于预期列:
如果你想推广这个函数,你实际上可以传递你想要替换的东西,使它更通用
一种方法是将^{} 与查找括号之间内容的模式一起使用,替换参数可以是在匹配对象上使用
replace
的lambda:有关
pat=
中的内容的解释,请参见here说明:
beginning until parenthesis and then hyphen
和after hyphen until parenthesis and then optional additional stuff
的正则表达式组sum
再次将它们连接在一起NaN
,使用原始(combine_first
)中的值这样,连字符将被删除,而不是替换为空格。如果需要空格,可以使用
apply
而不是sum:无论哪种方式,这都不适用于多组括号
相关问题 更多 >
编程相关推荐