如何加快将大字符串写入python文件的速度

问题描述 投票:0回答:1

因此,我有一个1 Gb输入txt文件(100万行* 10列),我正在使用python处理此输入以获取一些计算出的信息,并将每条信息(从1 M行中)添加到字符串中,最后保存。我尝试运行脚本,但意识到随着字符串变大,过程变得越来越慢。我想知道是否可以将每行追加到输出中并删除先前的缓冲行以减少内存使用?谢谢。代码示例:

import pandas as pd

# main_df.txt has more than 1 million lines and 10 columns
main_df = pd.read_csv('main_df.txt')

"""
processing main_df into new_df, but new_df still has 1 M lines in the end
"""

sum_df = ''
# I'm guessing sum_df gets super big here as it goes, which uses up memory and slows the process . 
# I have a bunch of complex loops, to simplify, I will just make an example for one single loop:
for i in range(len(new_df)):
    sum_df += new_df.loc[i, 1] + '\t' + new_df.loc[i, 3] + '\t' + new_df.loc[i, 5] + '\n'

with open('out.txt', 'w') as w:
    w.write(sum_df)
python pandas
1个回答
0
投票

很难说出您的目标是什么,但是有些事情可能会有所帮助。这是一个示例df。

new_df = pd.DataFrame({0:np.random.choice(list(string.ascii_lowercase), size=(10)),
                       1:np.random.choice(list(string.ascii_lowercase), size=(10)),
                       2:np.random.choice(list(string.ascii_lowercase), size=(10)),
                       3:np.random.choice(list(string.ascii_lowercase), size=(10)),
                       4:np.random.choice(list(string.ascii_lowercase), size=(10)),
                       5:np.random.choice(list(string.ascii_lowercase), size=(10)),
                       6:np.random.choice(list(string.ascii_lowercase), size=(10))})

print(new_df)

    0   1   2   3   4   5   6
0   z   k   o   m   s   k   w
1   x   g   k   k   h   b   v
2   o   y   m   r   g   l   r
3   i   n   m   q   o   j   h
4   r   d   s   r   s   p   s
5   t   o   d   w   e   b   a
6   t   z   w   y   q   s   n
7   r   r   d   x   b   s   s
8   g   v   h   m   w   c   l
9   r   v   y   i   w   i   z

您的代码输出:

sum_df = '' # this is a string, not a df

for i in range(len(new_df)):
    sum_df += new_df.loc[i, 1] + '\t' + new_df.loc[i, 3] + '\t' + new_df.loc[i, 5] + '\n'

print(sum_df)



i   k   z
x   g   o
y   l   x
g   s   l
p   h   e
u   s   v
r   u   l
m   j   e
q   k   f
d   p   b

我不是很确定其他循环应该做什么,但是示例中的循环看起来只占用了第1、3和5列。因此,除了执行for循环之外,您还可以这样做。

sum_df = new_df[[1,3,5]]
print(sum_df)

   1  3  5
0  k  m  k
1  g  k  b
2  y  r  l
3  n  q  j
4  d  r  p
5  o  w  b
6  z  y  s
7  r  x  s
8  v  m  c
9  v  i  i

然后将其保存为.txt。

sum_df.to_csv('new_df.txt', header=None, index=None, sep='\t')

通常来说,您要避免循环遍历dfs。如果您需要执行比示例更复杂的操作,则可以使用pd.apply()沿df的轴应用自定义函数。如果必须循环df,则df.itertuples或df.iterrows()优于for循环,因为它们使用Datanovice的评论中提到的生成器。

© www.soinside.com 2019 - 2024. All rights reserved.