目前我在构建一个合并财务报表系统,从财务系统里抓数然后做数据清洗和计算,其中清洗阶段主要使用pandas完成。
抓的数据中,数字都用千分位符隔开,导入pandas时被识别为object类型而不是float,影响后续计算,因此需要做类型转换。
temp_file = pd.read_csv(file_name, index_col=None, low_memory=False)
col_float = ['期初余额', '本期借方', '本期贷方', '借方累计', '贷方累计', '期末余额']
for c in col_float:
if isinstance(temp_file[c], object):
temp_file[c] = temp_file[c].str.replace(',', '')
temp_file[c].fillna(0, inplace=True)
temp_file[c] = temp_file[c].astype(float)
Traceback (most recent call last):
File "E:/Flask/Consol_demo/test consol.py", line 12, in <module>
df = rf.pl_clean(r'e:test filestables1801PLCZ.csv')
File "E:FlaskConsol_democonsolappsdata_washer.py", line 51, in pl_clean
temp_file[c] = temp_file[c].str.replace(',', '')
File "E:FlaskConsol_demovenvlibsite-packagespandascoregeneric.py", line 4372, in __getattr__
return object.__getattribute__(self, name)
File "E:FlaskConsol_demovenvlibsite-packagespandascoreaccessor.py", line 133, in __get__
accessor_obj = self._accessor(obj)
File "E:FlaskConsol_demovenvlibsite-packagespandascorestrings.py", line 1895, in __init__
self._validate(data)
File "E:FlaskConsol_demovenvlibsite-packagespandascorestrings.py", line 1917, in _validate
raise AttributeError("Can only use .str accessor with string "
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in panda
if isinstance(temp_file[c], object):
temp_file[c] = temp_file[c].str.replace(',', '')
正确答案
将temp_file[c] = temp_file[c].str.replace(‘,’, ‘’)
替换为temp_file[c] = temp_file[c].astype(str).replace(‘,’, ‘’)
参考链接:
https://segmentfault.com/q/1010000015970286
原文地址:https://blog.csdn.net/weixin_46713695/article/details/125816453
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_34828.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。