Python:如果在列标签中找到,则替换给定字符
我有一个df,看起来像这样: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
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