You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas保存CSV报错‘str’无to_csv属性,求数据处理方案

问题分析与解决

报错原因

直接触发'str' object has no attribute 'to_csv'错误的是这段代码:

df = str(round(df, 2))
df = pd.to_numeric(df, errors="ignore")
  • str(round(df, 2))会把整个DataFrame对象转换成字符串格式,此时df已经不再是DataFrame类型。
  • 后续用pd.to_numeric处理字符串对象,因为errors='ignore'参数的存在,无法转换的内容会原样返回,最终df还是字符串类型,而字符串没有to_csv方法,所以报错。

pd.to_numeric用法正误判断

你用pd.to_numeric(df, errors='ignore')处理整个DataFrame的方式不正确:

  • pd.to_numeric的设计目标是处理单个Series(即DataFrame的某一列),不能直接传入整个DataFrame。
  • 如果要批量处理DataFrame中的非数值类型(比如None),应该对每一列应用该方法,用df.apply()实现。

修正后的完整代码

import pandas as pd
import numpy as np


df = pd.read_csv("D:\\data_ana\\\\2022.07.27_at_10.00.33.csv")
index = 5

cols_in_the_slice = df.loc[
    :,
    (
        f"Objects[{index}].General.u_MeasuredTimeStamp",
        f"Objects[{index}].General.u_LifeCycles",
        f"Objects[{index}].KinematicRel.f_DistX",
        f"Objects[{index}].KinematicRel.f_DistY",
        f"Objects[{index}].KinematicRel.f_VrelX",
    ),
].columns


other_cols = pd.Index(["TimeStamp", "Velocity", "Accel", "YawRate"])
all_cols = other_cols.union(cols_in_the_slice, sort=False)

df = df[all_cols]

df.rename(
    columns={
        f"Objects[{index}].General.u_MeasuredTimeStamp": "Obj_TimeStamp",
        f"Objects[{index}].General.u_LifeCycles": "Age",
        f"Objects[{index}].KinematicRel.f_DistX": "K_DistX",
        f"Objects[{index}].KinematicRel.f_DistY": "K_DistY",
        f"Objects[{index}].KinematicRel.f_VrelX": "K_VrelX",
        f"Objects[{index}].KinematicRel.f_VrelY": "K_VrelY",
    },
    inplace=True,
)

# 修正部分:批量转换列类型并保留两位小数
df = df.apply(pd.to_numeric, errors='ignore')
df = df.round(2)

# 保存CSV,无需赋值给df
df.to_csv(r"D:\\data_ana\\duplicate_2022.07.27_at_10.00.33.csv", index=False)

内容的提问来源于stack exchange,提问作者Praveen Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 03:24:24