我需要为 Python 作业实现多线程。
我有一本字典,该字典中的每个键(大约 40 个)都是带时间戳的 pandas 数据框。大多数数据框有 100,000 多行。它们的时间戳是"%Y-%m-%d %H:%M:%S"
格式的字符串。
要转换带时间戳的字符串,我使用以下函数:
def to_dt(df):
df['timestamp'] = df['timestamp'].map(lambda n: pd.to_datetime(n, format='%Y-%m-%d %H:%M:%S'))
return df
所以我想把每个进程to_dt(df)
放在一个单独的线程中。我怎样才能做到这一点?
为简化起见,让我们考虑以下设置:
def to_dt(df):
df['timestamp'] = df['timestamp'].map(lambda n: pd.to_datetime(n, format='%Y-%m-%d %H:%M:%S'))
return df
# empty dictionary
d_test = {}
# dataframe with single string timestamp column
df = pd.DataFrame(columns=['st_dt'])
# populate dataframe with 1000 timestamp rows
for i in range(1000):
df.loc[len(df)] = ['2018-10-02 10:00:00']
# add 20 instances of the dataframe to the dictionary with keys in format "a0" to 'a19'
for i in range(20):
d_test['a'+str(i)] = df
现在我们怎样才能使每次迭代
for i in range(20):
to_dt(d_test['a'+str(i)])
在单独的线程中运行?