将 pandas 数据帧的每一行写入一个新的文本文件 - pythonic 方式
Write each row of pandas dataframe into a new text file - pythonic way
如果有一种方法可以按行解析 pandas 数据框并将每一行的内容写入新的文本文件,我正在尝试 google。我的数据框由一个名为 Reviews 的列组成。
我想对电影评论进行一些情绪分析,我需要将每条评论都放在一个单独的文本文件中。有人可以帮我吗。
它仍然效率低下,但由于需要它,这里有一个可能的解决方案。
import pandas as pd
from io import StringIO
data="""
column1 column2
c1 c2
c3 c4
c5 c6
"""
df = pd.read_csv(StringIO(data), delimiter='\s+')
i=0
for row in df.values:
filename = 'testdir/review{}.csv'.format(i)
row.tofile(filename, sep=",", format="%s")
i+=1
这会将值作为数组并在循环内 write the data to a csv file named review0.csv
, review1.csv
... Another solution is to use pd.to_csv
并指定 chunk
我写过这样的东西,而且很管用。无论如何感谢你们的投入
for index, row in p.iterrows():
if i > len(p):
break
else:
f = open(str(i)+'.txt', 'w')
f.write(row[0])
f.close()
i+=1
其中 p 是数据帧。
这是另一种方法。如果目标文件夹不存在,这将创建一个目标文件夹。
import pandas as pd
from pathlib import Path
root_location = Path("/my/root/path")
os.makedirs(root_location, exist_ok=True)
df = pd.read_csv(my_csv) # for example
for index, row in df.iterrows():
with open(root_location / (str(row["file_name"]) + ".txt"), "w") as f:
f.write(str(row["file_contents"]))
如果有一种方法可以按行解析 pandas 数据框并将每一行的内容写入新的文本文件,我正在尝试 google。我的数据框由一个名为 Reviews 的列组成。
我想对电影评论进行一些情绪分析,我需要将每条评论都放在一个单独的文本文件中。有人可以帮我吗。
它仍然效率低下,但由于需要它,这里有一个可能的解决方案。
import pandas as pd
from io import StringIO
data="""
column1 column2
c1 c2
c3 c4
c5 c6
"""
df = pd.read_csv(StringIO(data), delimiter='\s+')
i=0
for row in df.values:
filename = 'testdir/review{}.csv'.format(i)
row.tofile(filename, sep=",", format="%s")
i+=1
这会将值作为数组并在循环内 write the data to a csv file named review0.csv
, review1.csv
... Another solution is to use pd.to_csv
并指定 chunk
我写过这样的东西,而且很管用。无论如何感谢你们的投入
for index, row in p.iterrows():
if i > len(p):
break
else:
f = open(str(i)+'.txt', 'w')
f.write(row[0])
f.close()
i+=1
其中 p 是数据帧。
这是另一种方法。如果目标文件夹不存在,这将创建一个目标文件夹。
import pandas as pd
from pathlib import Path
root_location = Path("/my/root/path")
os.makedirs(root_location, exist_ok=True)
df = pd.read_csv(my_csv) # for example
for index, row in df.iterrows():
with open(root_location / (str(row["file_name"]) + ".txt"), "w") as f:
f.write(str(row["file_contents"]))