繁体   English   中英

多线程 python 数周天数数据集

[英]Multithread python count week days several dataset

大家好,我正在尝试在 python 中使用多线程

def get_weekday_data(t_index,file_name):
    """
   get dates (columna Date/Time).
    """
    #
    logging.info("[T{}]\tStarted with url {}".format(t_index, file_name))
    data=pd.read_csv(path+file_name)
    data['Date/Time']=pd.to_datetime(data['Date/Time'], 
    infer_datetime_format=True) 
    week_day_data=pd.DataFrame(data['Date/Time'].apply(lambda x: 
    x.strftime('%A')))
    week_day_data_2=pd.DataFrame(week_day_data['Date/Time'].value_counts())
    week_day_data_2.reset_index(inplace=True)
    week_day_data_2.sort_values('index',inplace=True)
    print(week_day_data_2)



  logging.info("[T{}]\tEnd".format(t_index))
  return week_day_data_2

我有这个 function 并且我想使用多线程将 function 应用到 6 个数据集我尝试以下但我不知道如何连接每个线程的结果。 我正在学习如何使用多线程和多进程。 但是我不知道如何获取每个线程的output

%%time
threads = []

#  6 threads execute get_weekday_data 

for i, num in enumerate(files_to_read):
    print('now')
    thread = Thread(target= get_weekday_data, args=(i,num))
    threads.append(thread)
    thread.start()

# Espera a que los 6 threads finalicen
for i, thread in enumerate(threads):
    logging.info("[M]\tWaiting to join thread {}".format(i))
    thread.join()
    logging.info("[M]\tThread {} joined!".format(i))

logging.info("[M]\tDONE!")

我真的推荐使用joblib ,它更容易使用。 您可以使用以下方式安装它:

pip install joblib

你可以像这样简单地使用它:

from joblib import Parallel, delayed


result = Parallel(n_jobs=4, backend="threading")(
            delayed(get_weekday_data)(idx, file_name) \
                for idx, file_name in enumerate(files_to_read))

result是基于插入排序的所有数据的列表。 您甚至可以从n_jobs参数控制有多少线程一起运行

您可以使用ThreadPoolExecutorProcessPoolExecutor的 map function

这是一个可能的实现

from concurrent.futures.thread import ThreadPoolExecutor

with ThreadPoolExecutor() as executor:
    results = executor.map(get_weekday_data, range(len(files_to_read)), files_to_read)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM