Python 如果包含在括号中,则替换列的字符串值
我以以下数据帧为例:Python 如果包含在括号中,则替换列的字符串值,python,python-3.x,pandas,string,dataframe,Python,Python 3.x,Pandas,String,Dataframe,我以以下数据帧为例: 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']}) 我发现很多帖
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']})
我发现很多帖子都有人想从字符串或类似情况中删除括号,但在我的例子中,我希望保留字符串的原样,只是我想删除字符串括号内的连字符
有人对我如何做到这一点有什么建议吗
str.split()。我想不出一个办法来解决这个问题
在这种情况下,此假设列中值的理想结果为:
'fruit-of the-loom (sometimes never)',
'yes',
'ok (not possible) I will try',
'vegetable',
'poultry',
'poultry'`
我应该多花点时间考虑这个问题
这就是我想出的解决办法”
计数括号,替换正确计数范围内的内容
def inside_parens(string):
parens_count = 0
return_string = ""
for a in string:
if a == "(":
parens_count += 1
elif a == ")":
parens_count -= 1
if parens_count > 0:
return_string += a.replace('-', ' ')
else:
return_string += a
return return_string
return return_string
完成后,将其应用于预期列:
df['col_1'] = df['col_1'].apply(inside_parens)
如果您想泛化函数,实际上可以传递您想要替换的内容,使其更通用。一种方法是使用模式查找括号之间的内容,替换参数可以是lambda,在匹配对象上使用replace
:
print (test['type'].str.replace(pat='\((.*?)\)',
repl=lambda x: x.group(0).replace('-',' ')))
0 fruit-of the-loom (sometimes never)
1 yes
2 ok (not possible) I will try
3 vegetable
4 poultry
5 poultry
Name: type, dtype: object
可以找到pat=
中的内容说明
说明:
- 提取
的正则表达式组,从括号开始,然后连字符
和在连字符之后,直到括号,然后是可选的附加内容
- 使用
sum
- 其中,
NaN
,使用原始值(combine\u first
)
这样可以删除连字符,而不是用空格代替。如果需要空格,可以使用apply
而不是sum:
test.type = (test.type.str.extract('(.*?\(.*?)-(.*?\))(.*)')
.apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
.combine_first(test.type))
无论哪种方式,这都不适用于多组括号
test.type = (test.type.str.extract('(.*?\(.*?)-(.*?\))(.*)')
.apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
.combine_first(test.type))