将数据帧的内容写入 .txt 文件,每行一个文件?
Write contents of dataframe to .txt files with one file per row?
我有一个包含 n 行的两列数据框。
Col1 Col2
123 abc
456 def
我想遍历数据框并为每一行创建一个文本文件。第一列是文本文件名,第二列是文本文件内容。
结果:
- 123.txt 内容为 abc
- 456.txt 内容为 def
这是一种使用 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)
这会将文本文件保存在您的工作目录中。
一个简单的基础 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)
我有一个包含 n 行的两列数据框。
Col1 Col2
123 abc
456 def
我想遍历数据框并为每一行创建一个文本文件。第一列是文本文件名,第二列是文本文件内容。
结果:
- 123.txt 内容为 abc
- 456.txt 内容为 def
这是一种使用 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)
这会将文本文件保存在您的工作目录中。
一个简单的基础 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)