繁体   English   中英

如何将append dataframe output to.txt文件

[英]How to append the dataframe output to .txt file

TI_分档

我想从我的 excel 工作表中提取特定数据并将这些数据保存 & append 到我的 existing.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

尝试使用df.to_string()将过滤后的 dataframe 转换为字符串,并将其写入文本文件。 如果文本文件中不需要索引,也可以在to_string()中传递index=False

这是一个给你的例子:-

df1 = df.iloc[:, [6, 7]]

with open("try.txt",'a') as fa :
    fa.write(df1.to_string(index=False))

这是我正在使用的示例数据的图像:-

在此处输入图像描述

这是文本文件中的 output:-

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM