使用列名作为要替换的字符串值执行字符串替换

2024-09-29 19:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的数据帧上执行一个字符串替换,在这个数据帧中我在一列中找到“X”的所有实例,并用列名替换它。你知道吗

Name  FFF1  H0L1
  -    L     -
  -    X     L
  X    -     -
  -    -     X

更换后的结果

Name     FFF1      H0L1
  -      FFF1        -
  -      FFF1      H0L1
Name      -          -
  -       -        H0L1

这似乎很简单,我只是对如何“引用”列名感到困惑。思想?你知道吗


Tags: 数据实例字符串name思想fff1h0l1
2条回答

“apply”方法将列作为“name”属性对应于列名的序列进行迭代:

df.apply(lambda col: col.where(~col.str.contains("X"), \
                        col.str.replace("X",col.name)) )

更好的是:

df.apply(lambda col: col.str.replace("X",col.name))

编辑: 回答附加问题: 使用正则表达式:

#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
"""

编辑2: 如果单元格中始终有一个字符要替换:

df.apply(lambda col: col.replace(["X","L"],col.name))

您可以使用df.where

df = pd.DataFrame({"A": ['-', 'X'],
                   'B': ['X', '-']})
df.where(df.eq('X'), df.columns)

输出:

   A  B
0  A  X
1  X  B

相关问题 更多 >

    热门问题