[EDIT]ローランドコメントで述べたように、標準のPython実装では、このポストは、CPUのパフォーマンスを改善するために、すべてのソリューションを提供していません。
標準的なPythonの実装では、スレッドはCPUバインドされたタスクで実際にパフォーマンスを改善しません。一度に1つのスレッドだけがPythonバイトコードを実行できるように強制する「グローバルインタープリタロック」があります。これは、メモリ管理の複雑さを抑えるために行われました。
異なる機能に異なるスレッドを使用しようとしましたか?
データフレームを列に分割し、複数のスレッドを作成するとします。次に、各スレッドを割り当てて、関数を列に適用します。あなたは十分な処理能力を持っている場合、あなたは多くの時間を得ることができるかもしれない:250万のレコードの場合
from threading import Thread
import pandas as pd
import numpy as np
from queue import Queue
from time import time
# Those will be used afterwards
N_THREAD = 8
q = Queue()
df2 = pd.DataFrame() # The output of the script
# You create the job that each thread will do
def apply(series, func):
df2[series.name] = series.map(func)
# You define the context of the jobs
def threader():
while True:
worker = q.get()
apply(*worker)
q.task_done()
def main():
# You import your data to a pandas dataframe
df = pd.DataFrame(np.random.randn(100000,4), columns=['A', 'B', 'C', 'D'])
# You create the functions you will apply to your columns
func1 = lambda x: x<10
func2 = lambda x: x==0
func3 = lambda x: x>=0
func4 = lambda x: x<0
func_rep = [func1, func2, func3, func4]
for x in range(N_THREAD): # You create your threads
t = Thread(target=threader)
t.start()
# Now is the tricky part: You enclose the arguments that
# will be passed to the function into a tuple which you
# put into a queue. Then you start the job by "joining"
# the queue
for i, func in enumerate(func_rep):
worker = tuple([df.iloc[:,i], func])
q.put(worker)
t0 = time()
q.join()
print("Entire job took: {:.3} s.".format(time() - t0))
if __name__ == '__main__':
main()
てくださいサンプル入力と希望の(出力)データセット。 [良い再現可能なパンダの例を作る方法]を読んでください。(http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – MaxU
あなたはあなたのコードは遅いですか? –
@RolandSmith、ネストされたループを推測させてください。 ;-) – MaxU