在 python 编码过程中, 总会遇到各种各样的小问题, 我想着记录下来, 以备查用, 总结过去, 是为了更好的思考与进步.
一. 去除变量中 (标题中) 多余的字符
数据处理过程中, 遇到这样的情况:
y=['月份', 'X2', '月份. 1', 'X2.1', '月份. 2', 'X2.2', '月份. 3', 'X2.3']
1. 可以用切片的方法
- y_new=[]
- for i in y:
- print(i[:2])
- y_new.append(i[:2])
- print(y_new)
2. 可以用 strip 方法
- x='X2.1'
- x.strip('.1')
也可以用 rstrip,lstrip; 分别去除左, 右的字符.
3. 正则表达式
- x='X2.1'
- re.sub('[/.\d]','',x)
若是在处理 dataframe 中遇到呢? 把标题中的多余的字符去掉, 可以用 map 函数, 比如:
data.columns=map(lambda x:x[:2],data.columns)
当然, 也可以正则去去除, 也可以用 replace:str.replace(old, new[, max]) , 总之, 方法很灵活, 思想很灵活.
二. 解决 to_csv 乱码问题
data.to_csv('XXXXX.csv',index=False,encoding='utf_8_sig') 加上 encoding='utf_8_sig'就行, index=False 表示没有 index 列, 很方便实用.
来源: https://www.cnblogs.com/jin-liang/p/8798975.html