I have a csv in the following format:
0 | Hello
1 | Hi
2 | GoodDay
I need to copy each row to a text file, so output will be:
0.txt -> Hello
1.txt -> Hi
2.txt -> GoodDay
I try (edited):
df=pd.read_csv('result.csv')
for x in df.iterrows():
pd.df([x[1][1]]).to_csv(str(x[1][0])+".txt", header=False, index=False)
I am using Python and Pandas.
答案 0 :(得分:1)
首先按values
转换为ndarray
,然后使用tofile
:
for row in df.values:
#print row
row[1:].tofile(str(row[0])+'.txt', sep="\t", format="%s")
read_csv
的解决方案:
import pandas as pd
import io
temp=u"""
0|Hello
1|Hi
2|GoodDay"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="|", header=None)
print (df)
0 1
0 0 Hello
1 1 Hi
2 2 GoodDay
for row in df.values:
#print row
row[1:].tofile(str(row[0])+'.txt', sep="\t", format="%s")
编辑:
包含iterrows
和to_csv
的另一个解决方案,但它在每个txt
文件中添加了空行:
for _, s in df.iterrows():
s.iloc[1:].to_csv(str(s.iloc[0]) + '.txt', index=False, header=False)