#df.apply(lambda col: col.str.replace(r"([^X]|^)(X)([^X]|$)",r"\1"+col.name+r"\3")) # didn't work correctly in all situation, e.g.: "aXbXcXd"
df.apply(lambda col: col.str.replace(r"([^X]|^)(X)(?=[^X]|$)",r"\1"+col.name))
""" The details:
We create three pattern groups: (...)
[^X] can be any char but X (^ in square br. negates the chars)
^ as a separate char means start of string;
$ means end of string;
| means 'or'.
\1 and \2 mean the corresponding groups;
(?=...) lookahead check
"""
“apply”方法将列作为“name”属性对应于列名的序列进行迭代:
更好的是:
编辑: 回答附加问题: 使用正则表达式:
编辑2: 如果单元格中始终有一个字符要替换:
您可以使用
df.where
:输出:
相关问题 更多 >
编程相关推荐