基于正则表达式熊猫更新字段格式



df 有:

id  type
0   [a]+[b]-[c]
1   [b]-[c]
2   [a]*[d]

DF想要:

id  type
0   x['a']+x['b']-x['c']
1   x['b']-x['c']
2   x['a']*x['d']

对于每一行,我需要在方括号内的项目周围添加引号,并在每个开放方括号前面加上 x

当有更简单的方法时,为什么要使用正则表达式:

import pandas as pd
df = pd.DataFrame({
"id": [0, 1, 2],
"type": ["[a]+[b]-[c]", "[b]-[c]", "[a]*[d]"]
})
df["type"] = df["type"].str.translate(str.maketrans({"[": "x['", "]": "']"}))
import re
for i in df.index:
df.at[i, 'type'] = re.sub('[([^]]*)]', 'x['g<1>']', df.at[i, 'type'])

Docs for re.sub. 我们用'[([^]]*)]'捕获每个偏执及其内容,并将其替换为x['(contents of the paranthesis)']。就这么简单:)

这是一种使用列表理解的方法:

import re
df['type'] = [ ''.join("x{}".format(re.sub(r'([a-z]+)', r"'1'", x)) 
if x not in ['-', '+', '*'] 
else x for x in re.split("(+|-|*)", s)) 
for s in df['type']]

最新更新