2015-02-07 63 views
-1

我有一个两列数据框与nrows。将数据帧的内容写入.txt文件,每行一个文件?

Col1 Col2 
123 abc 
456 def 

我想遍历数据框并为每一行创建一个文本文件。第一列是文本文件名,第二列是文本文件内容。

结果:

  • 123.txt与内容ABC
  • 456.txt与内容高清
+0

我假设你使用熊猫吗? – MattDMo 2015-02-07 00:28:59

+0

是的我正在使用熊猫 – 2015-02-08 00:58:03

回答

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) 

这会将文本文件保存在您的工作目录中。

+0

这个解决方案非常完美,谢谢JAB! – 2015-02-09 17:13:31

0

一个简单的基础蟒蛇的解决办法是(不使用大熊猫):

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)