目前我在构建一个合并财务报表系统,从财务系统里抓数然后做数据清洗和计算,其中清洗阶段主要使用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 files\tables\1801PLCZ.csv')
  File "E:\Flask\Consol_demo\consol\apps\data_washer.py", line 51, in pl_clean
    temp_file[c] = temp_file[c].str.replace(',', '')
  File "E:\Flask\Consol_demo\venv\lib\site-packages\pandas\core\generic.py", line 4372, in __getattr__
    return object.__getattribute__(self, name)
  File "E:\Flask\Consol_demo\venv\lib\site-packages\pandas\core\accessor.py", line 133, in __get__
    accessor_obj = self._accessor(obj)
  File "E:\Flask\Consol_demo\venv\lib\site-packages\pandas\core\strings.py", line 1895, in __init__
    self._validate(data)
  File "E:\Flask\Consol_demo\venv\lib\site-packages\pandas\core\strings.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

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐