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

如何将DataFrame输出追加至TXT文件?现有代码报错求助

问题场景

TI_Binning

我想要从Excel工作表中提取特定数据,并将这些数据保存并追加到已有的.txt文件中。以下是我当前的代码,但在将数据保存到TXT文件时出现错误:

import pandas as pd

df = pd.read_excel(r"C:\Users\a0229010\Desktop\PP177507.xls", 'TI_Binning', skiprows=2)
df = df.iloc[:, [6, 7]]

import numpy as np

with open(r"C:\Users\a0229010\Desktop\TI_Bin.txt", "ab") as f:
    np.savetxt(f, df)  #this is the line where i am getting the error
错误原因 & 修复方案

核心问题

你用"ab"二进制模式打开文件,但np.savetxt是专门处理文本文件的写入工具,二进制模式和文本写入逻辑不匹配,直接会触发错误;另外DataFrame如果包含非数值类型(比如字符串、空值),直接传给np.savetxt也会报错。

方案1:修正numpy写法

改用文本模式打开文件,同时将DataFrame转为numpy数组传入:

import pandas as pd
import numpy as np

df = pd.read_excel(r"C:\Users\a0229010\Desktop\PP177507.xls", 'TI_Binning', skiprows=2)
df = df.iloc[:, [6, 7]]

# 用文本追加模式,指定编码避免乱码
with open(r"C:\Users\a0229010\Desktop\TI_Bin.txt", "a", encoding="utf-8") as f:
    # fmt参数根据数据类型调整:%s是字符串,%f是浮点数,%d是整数
    np.savetxt(f, df.values, fmt="%s")

方案2:用pandas原生方法更简便

不需要额外导入numpy,直接用to_csv实现追加,更适配DataFrame:

import pandas as pd

df = pd.read_excel(r"C:\Users\a0229010\Desktop\PP177507.xls", 'TI_Binning', skiprows=2)
df = df.iloc[:, [6, 7]]

# mode="a"表示追加,header=False不写表头,index=False不保留行索引,sep可自定义分隔符
df.to_csv(r"C:\Users\a0229010\Desktop\TI_Bin.txt", mode="a", header=False, index=False, sep=" ")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:20:30