为什么在 python 中使用 apply map 函数替换 header 名称中不需要的字符时出现错误?
我的 DF header (名称)包含:
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: []
关于python - 为什么在 python 中使用 apply map 函数替换 header 名称中不需要的字符时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42415829/