目前我在构建一个合并财务报表系统,从财务系统里抓数然后数据清洗和计算,其中清洗阶段主要使用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

发表回复

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