[英]Python: How to quickly create a pandas data frame with only specific columns from a big excel sheet?
[英]How to create a big file quickly with Python
我有以下用於生成大文本文件的代碼:
d = 3
n = 100000
f = open("input.txt",'a')
s = ""
for j in range(0, d-1):
s += str(round(random.uniform(0,1000), 3))+" "
s += str(round(random.uniform(0,1000), 3))
f.write(s)
for i in range(0, n-1):
s = ""
for j in range(0, d-1):
s += str(round(random.uniform(0,1000), 3))+" "
s += str(round(random.uniform(0,1000), 3))
f.write("\n"+s)
f.close()
但是,即使生成 5GB 的數據似乎也很慢。
我怎樣才能讓它變得更好? 我希望輸出是這樣的:
796.802 691.462 803.664
849.483 201.948 452.155
144.174 526.745 826.565
986.685 238.462 49.885
137.617 416.243 515.474
366.199 687.629 423.929
嗯,當然,整個事情都是 I/O 綁定的。 您無法以比存儲設備寫入文件的速度更快地輸出文件。 撇開這一點不談,可以進行一些優化。
您從幾個較短的字符串構建一個長字符串的方法是次優的。 你是說,本質上, s = s1 + s2
。 當您告訴 Python 執行此操作時,它會連接兩個字符串對象以創建一個新的字符串對象。 這很慢,尤其是重復時。
更好的方法是將單個字符串對象收集到列表或其他可迭代對象中,然后使用join
方法將它們一起運行。 例如:
>>> ''.join(['a', 'b', 'c'])
'abc'
>>> ', '.join(['a', 'b', 'c'])
'a, b, c'
這不是通過n-1 個字符串連接來連接n 個字符串,而是一步完成整個事情。
還有很多重復的代碼可以組合。 這是一個更簡潔的設計,仍然使用循環。
import random
d = 3
n = 1000
f = open('input.txt', 'w')
for i in range(n):
nums = []
for j in range(d):
nums.append(str(round(random.uniform(0, 1000), 3)))
s = ' '.join(nums)
f.write(s)
f.write('\n')
f.close()
一種更簡潔、更簡潔、更 Pythonic 的方法是使用列表理解:
import random
d = 3
n = 1000
f = open('input.txt', 'w')
for i in range(n):
nums = [str(round(random.uniform(0, 1000), 3)) for j in range(d)]
f.write(' '.join(nums))
f.write('\n')
f.close()
請注意,在這兩種情況下,我都分別編寫了換行符。 這應該比將它連接到字符串要快,因為無論如何 I/O 都會被緩沖。 如果我加入一個沒有分隔符的字符串列表,我只會在加入之前添加一個換行符作為最后一個字符串。
正如丹尼爾的回答所說,numpy 可能更快,但也許你還不想進入 numpy; 聽起來你在這一點上是一個初學者。
這可能會更快一點:
nlines = 100000
col = 3
for line in range(nlines):
f.write('{} {} {}\n'.format(*((round(random.uniform(0,1000), 3))
for e in range(col))))
或使用字符串格式:
for line in range(nlines):
numbers = [random.uniform(0, 1000) for e in range(col)]
f.write('{:6.3f} {:6.3f} {:6.3f}\n'.format(*numbers))
使用 numpy 可能更快:
import numpy
d = 3
n = 100000
data = numpy.random.uniform(0, 1000,size=(n,d))
numpy.savetxt("input.txt", data, fmt='%.3f')
我想如果您想使用無限循環並希望不受限制地制作如此大的文件,那就更好了,這樣使用效果更好
import random
d = 3
n = 1000
f = open('input.txt', 'w')
for i in range(10**9):
nums = [str(round(random.uniform(0, 1000), 3)) for j in range(d)]
f.write(' '.join(nums))
f.write('\n')
f.close()
單擊 ctr-c 時代碼不會停止
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.