Python - 将数据框写入 csv 文件
Python - write data frame into a csv file
我希望使用 python 将我的数据框写入 csv 文件。我正在使用 pandas 从我的输入文本构建数据框 file.This 是我的代码,
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'))
当我 运行 这在最后一行给我一个错误 -
c.writerow(字节(df, 'UTF-8'))
类型错误:'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(bytes(df, 'UTF-8'))
AttributeError: '_csv.writer' 对象没有属性 'write'
df.to_csv(path + filename)
我希望使用 python 将我的数据框写入 csv 文件。我正在使用 pandas 从我的输入文本构建数据框 file.This 是我的代码,
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'))
当我 运行 这在最后一行给我一个错误 - c.writerow(字节(df, 'UTF-8')) 类型错误:'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(bytes(df, 'UTF-8')) AttributeError: '_csv.writer' 对象没有属性 'write'
df.to_csv(path + filename)