【问题标题】:Adding special character to a column names向列名添加特殊字符
【发布时间】:2021-03-18 11:42:03
【问题描述】:

我有一个字符串格式的列名列表,如下所示:

lst = ["plug", "plug+wallet", "wallet-phone"]

我想添加df[]" ' ". 我正在使用正则表达式来替换它。但是当列表如下时,我使用的正则表达式可以正常工作:-

lst = [" 'plug'", "'plug'+'wallet'", "'wallet'-'phone'"]
x=[]
for l in lst: x.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]',l))
print(x)

结果为异常

x: [" df['plug']", "df['plug']+df['wallet']", "df['wallet']-df['phone']"]

但是当列表是这样的时候:

lst = ["plug", "plug+wallet", "wallet-phone"]
x=[]
y=[]
for l in lst: x.append(re.sub(r"('[^+\-*\/'\d]+')", r'\1',l))
for f in x:    y.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]',f))
print(x)
print(y)

这给出了:

['plug', 'plug+wallet', 'wallet-phone']
['plug', 'plug+wallet', 'wallet-phone']

我哪里错了?我是否遗漏了第一个正则表达式模式中的任何内容或没有正确传递 r'\1'

异常输出:

x: [" 'plug'", "'plug'+'wallet'", "'wallet'-'phone'"]    
y: [" df['plug']", "df['plug']+df['wallet']", "df['wallet']-df['phone']"]

【问题讨论】:

    标签: python regex list python-re


    【解决方案1】:

    这行得通:

    import re
    lst = ["plug", "plug+wallet", "wallet-phone"]
    x = [re.sub(r"([^+\-*\/'\d]+)", r"'\1'", l) for l in lst]
    y = [re.sub(r"('[^+\-*\/'\d]+')", r"df[\1]", l) for l in x]
    print(x)
    print(y)
    

    您的第一个正则表达式在 '' 上错误匹配,然后在替换主题中没有将其包含在 '' 中。

    在 Python 3.8.0 下测试。

    【讨论】:

    • 还有一个疑问。当列表值有(钱包电话)时。然后结果将是 df[('wallet'] - df[('phone'], 转换的最佳解决方案是什么 (df['wallet']-df['phone'])。我在尝试得到一个可以但找不到最佳解决方案的模式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多