Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如果在列标签中找到,则替换给定字符_Python_Replace_Pandas_Dataframe - Fatal编程技术网

Python:如果在列标签中找到,则替换给定字符

Python:如果在列标签中找到,则替换给定字符,python,replace,pandas,dataframe,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 fav

我有一个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") 

有什么想法吗?

您尝试的方法不起作用,因为
索引
没有这样的属性,但是我们可以做的是将列转换为一个系列,然后使用
str
replace
执行您想要的操作,您也应该能够对索引执行分析操作:

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