2015-02-07 66 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)