我有一个看起来像这样的 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,然后使用 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
关于Python Pandas : replace given character if found in column label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26180240/