【问题标题】:Write contents of dataframe to .txt files with one file per row?将数据框的内容写入 .txt 文件,每行一个文件?
【发布时间】:2015-02-07 10:04:25
【问题描述】:
我有一个包含 nrows 的两列数据框。
Col1 Col2
123 abc
456 def
我想遍历数据框并为每一行创建一个文本文件。第一列是文本文件名,第二列是文本文件内容。
结果:
- 123.txt 内容为 abc
- 456.txt 内容为 def
【问题讨论】:
标签:
python
python-2.7
pandas
【解决方案1】:
这是使用pandas 的一种方法。即使它有点难看,它也能完成工作,并且会让你上路。
import pandas as pd
df = pd.DataFrame({'food': ['eggs','eggs','ham','ham'],'co1':[20,19,20,21]})
for x in df.iterrows():
#iterrows returns a tuple per record whihc you can unpack
# X[0] is the index
# X[1] is a tuple of the rows values so X[1][0] is the value of the first column etc.
pd.DataFrame([x[1][1]]).to_csv(str(x[1][0])+".txt", header=False, index=False)
这会将文本文件保存在您的工作目录中。
【解决方案2】:
一个简单的基本 python 解决方案是(不使用 PANDAS):
lines = ["123 abc","456 def"]
def writeToFile(line):
words=line.split()
f = open(words[0]+'.txt','wb')
f.write(words[1])
f.close()
map(writeToFile,lines)