Skip to main content
 首页 » 编程设计

python之为什么我在 python 中使用 apply map 函数替换标题名称中不需要的字符时出错

2024年10月01日32TianFang

为什么在 python 中使用 apply map 函数替换 header 名称中不需要的字符时出现错误?

我的 DF 的标题(名称)包含:

Day % Change        $ Opening_Price         $ Close_Price 

我想要的是:

Day Change      Opening_Price       Close_Price 

名称中没有 % 符号和 $ 符号。

我在尝试什么:

DF = DF.applymap(lambda x: x if not '$' in str(x) else x.replace('$', '')) 
DF = DF.applymap(lambda x: x if not '%' in str(x) else x.replace('%', '')) 

但是上面给了我一个错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in position 10: ordinal not in range(128) 

请您参考如下方法:

我想你可以使用 str.replace然后通过 strip 删除开始和结束空格如有必要:

df.columns = df.columns.str.replace('[$%]', '').str.strip() 

print (df) 
Empty DataFrame 
Columns: [Day % Change, $ Opening_Price, $ Close_Price] 
Index: [] 
 
df.columns = df.columns.str.replace('[$%]', '').str.strip() 
 
print (df) 
Empty DataFrame 
Columns: [Day  Change, Opening_Price, Close_Price] 
Index: []