Can only use .str accessor with string values错误?
目前我在构建一个合并财务报表系统,从财务系统里抓数然后做数据清洗和计算,其中清洗阶段主要使用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(',', '')
求各位大神解答下如何解决这个问题呢,多谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将temp_file[c] = temp_file[c].str.replace(',', '')
替换为temp_file[c] = temp_file[c].astype(str).replace(',', '')