为什么在python中使用Apply Map函数替换标头名称中不需要的字符时出现错误?
我的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: []
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句