连根拔起并打扫

问题描述 投票:0回答:1

我正在尝试 uproot 的 dask 功能,即将分支加载到 dask 数组中。

不幸的是,我不明白为什么在尝试对这些数组执行计算时会发生这种情况,例如

import dask.array as da

tree = uproot.dask("file.root:tree", library = 'np')
branch_data = data["testbranch"]
mean = da.mean(branch_data).compute()

分支数据是一个二维数组,我想计算沿

axis=1
的平均值,即每一行的平均值。奇怪的是,输出和我一样:

np.mean(branch_data.T)

它以某种方式计算列的平均值。尝试添加

axis=1
会导致错误,指出维度为 1 的数组的轴超出范围。但是在分支上调用
compute()
来打印实际数据,它显然是预期的 2 维数组。其他方法(如 da.sum())也会发生这种情况。

编辑:这里我提供了一个重现问题的示例:

import numpy as np
import uproot

# creating sample file with tree
with uproot.recreate("test.root") as file:
    file["test_tree"] = {"test_branch": np.random.random((100,10))}

# Standard uproot
tree = uproot.open("./test.root:test_tree")
branch = tree["test_branch"].array(library = 'np')
mean = np.mean(branch, axis = 1)
print(mean)

# Uproot-Dask (Will compute mean columnwise. Strange...)
tree = uproot.dask("./test.root:test_tree", library = 'np')
branch = tree["test_branch"]
mean = np.mean(branch).compute()
print(mean)

#This will not work. Also strange
mean = np.mean(branch, axis = 1).compute()
print(mean)
python dask uproot
1个回答
0
投票

根据 uproot 手册,

uproot.dask()
函数“从
TTrees
返回未计算的 Dask 数组。”

使用您在示例代码中创建的

branch
对象,我可以通过调用
compute()
将其转换为普通的 Numpy 数组:

import numpy as np
import uproot

with uproot.recreate("test.root") as file:
    file["test_tree"] = {"test_branch": np.random.random((100,10))}

tree = uproot.dask("./test.root:test_tree", library = 'np')
branch = tree["test_branch"]
b_as_array = branch.compute()

继续互动:

>>> branch
dask.array<test_branch-from-uproot, shape=(100,), dtype=float64, chunksize=(100,), chunktype=numpy.ndarray>
>>> b_as_array = branch.compute()
>>> b_as_array.shape
(100, 10)
>>> np.mean(b_as_array, axis=0)
array([0.54450986, 0.48361194, 0.52477069, 0.50902231, 0.52925032,
       0.47309532, 0.49022969, 0.48736406, 0.5027256 , 0.56298907])

请注意,我必须使用

axis=0
来获得您想要的平均值,因为
np.mean(b_as_array)
仅返回一个数字,即所有 1000 个数字的平均值。

© www.soinside.com 2019 - 2024. All rights reserved.