目前我在构建一个合并财务报表系统,从财务系统里抓数然后数据清洗和计算,其中清洗阶段主要使用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进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注