我在熊猫数据框中有这样的东西:
Name,Total,Problem
Toyota,2,'They don’t need the oil consumed per trip, only a sum of manually counted damage.'
Mazda,1,'Hello, I got an engine error. See attachment below.'
Kia,2,'Client requires a confirmation that the information provided through CODEXXXX asap.'
Volkswagon,3,'During visual inspection of lights we have found a damage.'
我对获取df['Problem']
列并将其转换为文本文件感兴趣,因此文本文件的输出如下:
They don’t need the oil consumed per trip, only a sum of manually counted damage.
Hello, I got an engine error. See attachment below.
Client requires a confirmation that the information provided through CODEXXXX asap.
During visual inspection of lights we have found a damage.
我什至不需要文本文件中的索引,因为它将在文本标记应用程序中使用(并且必须以该格式输入)。即使df['Problem']
中的行/元素是一个段落长字符串,也必须在文本行中位于一行中。
答案 0 :(得分:0)
尝试以下代码:
with open('sample.txt','w') as f:
for data in list(df['Problem']):
f.write(data+'\n')
我希望这会有所帮助。
答案 1 :(得分:0)
系列的tolist()
方法可以在这里完成大部分工作。您可以使用join
在内存中构建整个文本(如果df不太大):
with open(file, 'w') as out:
print('\n'.join(df['Problem'].tolist()), file=out)
或者,如果要节省内存,请逐个打印:
with open(file, 'w') as out:
for line in df['Problem'].tolist():
print(line, file=out)