我创建了pandas数据框的全局变量。我希望子进程可以访问全局数据框,但是似乎子进程无法获取全局变量。
data = pd.DataFrame(data = np.array([[i for i in range(1000)] for j in range(500)]))
def get_sample(i):
print("start round {}".format(i))
sample = data.sample(500, random_state=i)
xs = sample.sum(axis=0)
if i < 10:
print(data.shape())
print(sample.iloc[:3, :3])
print("rount{} returns output".format(i))
return xs
samples = []
def collect(result):
print("collect called with {}".format(result[0][0].shape))
global samples
samples.extend(result)
ntasks = 1000
if __name__=='__main__':
samples = []
xs = pd.DataFrame()
"""sampling"""
pool = mp.Pool(cpu_count(logical=True))
print("start sampling, total round = {}".format(ntasks))
r = pool.map_async(get_sample, [j for j in range(ntasks)], callback=collect)
r.wait()
pool.close()
pool.join()
xs = pd.concat([sample for sample in samples], axis = 1, ignore_index=True)
xs = xs.transpose()
print("xs: ")
print(xs.shape)
print(xs.iloc[:10, :10])
全局数据框是数据。我希望在每个子进程中,函数get_sample都可以访问数据并从数据中检索一些值。为了确保子进程可以获取数据,我在每个子进程中打印出数据的形状。问题在于子进程似乎无法获取数据,因为当我运行它时,没有打印出数据的形状或部分样本。
此外,我收到错误消息: 追溯(最近一次通话): 文件“ sampling2c.py”,第51行,在 xs = pd.concat([用于样本的样本],轴= 1,ignore_index = True) 在concat中的文件“ /usr/usc/python/3.6.0/lib/python3.6/site-packages/pandas/tools/merge.py”,行1451 复制=复制) init 中的文件“ /usr/usc/python/3.6.0/lib/python3.6/site-packages/pandas/tools/merge.py”,行1484 引发ValueError('没有要连接的对象') 似乎get_sample函数未返回任何内容,采样失败。
但是,当我做一个实验来测试子进程是否可以访问全局变量时,它就可以工作。
df = pd.DataFrame(data = {'a':[1,2,3], 'b':[2,4,6]})
df['c1'] = [1,2,1]
df['c2'] = [2,1,2]
df['c3'] = [3,4,4]
df2 = pd.DataFrame(data = {'a':[i for i in range(100)], 'b':[i for i in range(100, 200)]})
l = [1, 2, 3]
Mgr = Manager()
results = []
def collect(result):
global results
#print("collect called with {}".format(result))
results.extend(result)
counter = 12
def sample(i):
print(current_process())
return df2.sample(5, random_state = i)
if __name__=='__main__':
pool = Pool(3)
r = pool.map_async(sample, [i for i in range(3)], callback = collect) #callback = collect
r.wait()
for res in results:
print(res)
每个子进程都可以访问全局变量df2。我不确定子进程为什么无法访问第一段代码中的数据。
答案 0 :(得分:0)
使用多处理程序生成进程时,新进程会在生成时获得状态的副本。
如果要在父进程或其他同级进程之间通信数据,则可以使用共享变量或处理共享对象的服务器进程进行通信。有关详细信息,请参见sharing-state-between-processes
如果改为使用线程,则各个线程都在同一上下文中运行,共享所有全局变量。因此,您无需执行任何特殊操作即可访问所有线程和主循环中的所有全局变量。
线程和多处理都有其优点和缺点,但这不是讨论它们的地方。