Python Pandas : replace given character if found in column label

标签 python replace pandas dataframe

我有一个看起来像这样的 df:

Label                        PG & PCF      EE-LV  Centre    UMP     FN  
Label                                                                    
Très favorable                   2.68       3.95    4.20   3.33   3.05   
Plutôt favorable                12.45      42.10   19.43   2.05   1.77   
Plutôt défavorable              43.95      41.93   34.93  20.15  15.97   
Très défavorable                37.28       9.11   41.44  70.26  75.99   
Je ne sais pas                   3.63       2.91    0.10   4.21   3.22

我只想将列标签或索引标签中找到的“&”替换为“and”。

我本以为这样的东西会起作用,但它没有......

dataframe.columns.replace("&","and") 

有什么想法吗?

最佳答案

您尝试的方法不起作用,因为 Index 没有这样的属性,但是我们可以做的是将列转换为 Series,然后使用 strreplace 来做你想做的事情,你也应该能够对索引进行类似的操作:

df.columns = pd.Series(df.columns).str.replace('&', 'and')
df
Out[307]:
                    PG and PCF  EE-LV  Centre    UMP
Label                                               
Très favorable            2.68   3.95    4.20   3.33
Plutôt favorable         12.45  42.10   19.43   2.05
Plutôt défavorable       43.95  41.93   34.93  20.15
Très défavorable         37.28   9.11   41.44  70.26
Je ne sais pas            3.63   2.91    0.00   4.21

关于Python Pandas : replace given character if found in column label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26180240/

相关文章:

python - 使用模糊正则表达式(Python)来纠正拼写

python - 解析Python函数中的外部方法调用?

c# - 如何在 C# 中将 char(10) [sql server] 替换为其他内容

python - MySql read_sql python 查询,带变量@

python-3.x - 为什么两个 DataFrame 在使用 `=` 时会被链接?

python - 类型错误 : object of type 'method' has no len()

python - 在 hello world prog 中获取错误消息 'NameError: global name ' kw'未定义'

python mysqldb 多个连接

sed - 如何只用sed替换一行中的最后一场比赛?

python - 用第一个条目替换列表中的元组