Python - 将数据框写入csv文件
问题描述:
我正在寻找使用python将我的数据框写入csv文件。我利用大熊猫建立从我输入的文本文件。这个数据帧是我的代码,Python - 将数据框写入csv文件
import pandas
import csv
txt_file = r"sida.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}
c = csv.writer(open("MYFILE.csv", "wb"))
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if k in txt_dict:
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
df=(pandas.DataFrame.from_dict(txt_dict, orient="index"))
print(df)
c.writerow(bytes(df, 'UTF-8'))
,当我运行这一点,让我在最后一行在这里的错误 - ℃。 Writer(字节(df,'UTF-8')) TypeError:'str'不支持缓冲接口。请帮助我。我希望我的数据框输出在我的csv文件中。提前致谢。
这是更新的代码,
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if k in txt_dict:
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
df=(pandas.DataFrame.from_dict(txt_dict, orient="index"))
print(df)
c.write(bytes(df, 'UTF-8'))
,而且我得到的错误是这样的,c.write(字节(DF, 'UTF-8')) AttributeError的: '_csv.writer'对象没有属性 '写'
http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-th e-buffer-interface –
是的。我经历了它。但我得到这个错误,当我尝试** c.write(bytes(df,'UTF-8')) AttributeError:'_csv.writer'对象没有属性'写'** –
添加你试过的以及您遇到的问题,以便人们可以更好地帮助您。 –