我正在嘗試更改 CSV 中列的日期格式。我知道有更簡單的方法可以做到這一點,但這里的目標是讓執行緒正常作業。我使用 Spyder 和 Python 3.8。我的代碼作業如下:
- 我創建了一個帶有更改日期格式的函式的執行緒類
- 我根據執行緒數將我的資料幀分成幾個資料幀
- 我為每個執行緒分配資料幀的一部分
- 每個執行緒更改其資料框中的日期格式
- 最后,我將所有資料幀連接成一個
“系列”是我的原始資料框。這是我的代碼:
import pandas as pd
import numpy as np
import threading
import time
from datetime import datetime
from threading import Thread
from time import process_time
serie=pd.read_csv('XXX.csv')
in_format = "%d/%m/%Y"
out_format = "%Y-%m-%d"
class MonThread (threading.Thread):
def __init__(self, num_thread):
threading.Thread.__init__(self)
self.num_thread = num_thread
#Thread function
def run(self):
for self.i in range(dataframes[self.num_thread].index[0], dataframes[self.num_thread].index[0] dataframes[self.num_thread].shape[0]):
date_formatee = datetime.strptime(dataframes[self.num_thread].loc[self.i, 'Date'], in_format).strftime(out_format)
dataframes[self.num_thread].loc[self.i, 'Date'] = date_formatee
nb_thread = 80
dataframes = []
#Df divided in several
for j in range(nb_thread):
a = j * (serie.shape[0] // nb_thread)
if j != nb_thread - 1 :
b = (j 1) * (serie.shape[0] // nb_thread)
df = serie.iloc[a:b,:]
else:
df = serie.iloc[a:,:]
b = serie.shape[0]
dataframes.append(df)
print("Intervalle", j, ": [", a, ",", b, "]")
tps1 = process_time()
print(tps1)
threads = []
for n in range(nb_thread):
t = MonThread(n)
t.start()
threads.append(t)
for t in threads:
t.join()
dataframe_finale = pd.concat(dataframes)
print("\n\n\n")
tps2 = process_time()
print(tps2)
print("temps d'éxécution : ")
print(tps2 - tps1)
它正在作業,但我發現執行時間很長,對于總共 100000 個值,在沒有執行緒的情況下處理大約需要 1min30,但是對于 80 個執行緒,我需要大約 30 秒,而對于 200 或 400 個執行緒,我會停滯在 30秒。我的代碼是壞的還是我受到了某些東西的限制?
uj5u.com熱心網友回復:
您是否嘗試過讓 Pandas 完成該系列的作業?
import pandas as pd
df = pd.read_csv('XXX.csv')
in_format = "%d/%m/%Y"
out_format = "%Y-%m-%d"
df['Date'] = pd.to_datetime(df['Date'], format=in_format).dt.strftime(out_format)
在我的 Macbook 上,這會在 5 秒內處理一百萬個條目。
另一種做同樣事情的方法(雖然沒有日期驗證)是
df['Date'] = df['Date'].str.replace(r"(\d )/(\d )/(\d )", r"\3-\2-\1", regex=True)
在大約 3.3 秒內完成作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488415.html
