- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我阅读了以下 SO thead现在我正在努力理解它。这是我的例子:
import dask.dataframe as dd
import pandas as pd
from dask.multiprocessing import get
import random
df = pd.DataFrame({'col_1':random.sample(range(10000), 10000), 'col_2': random.sample(range(10000), 10000) })
def test_f(col_1, col_2):
return col_1*col_2
ddf = dd.from_pandas(df, npartitions=8)
ddf['result'] = ddf.map_partitions(test_f, columns=['col_1', 'col_2']).compute(get=get)
它会在下面生成以下错误。我究竟做错了什么?此外,我不清楚如何将附加参数传递给 map_partitions
中的函数?
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\utils.py in raise_on_meta_error(funcname)
136 try:
--> 137 yield
138 except Exception as e:
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\core.py in _emulate(func, *args, **kwargs)
3130 with raise_on_meta_error(funcname(func)):
-> 3131 return func(*_extract_meta(args, True), **_extract_meta(kwargs, True))
3132
TypeError: test_f() got an unexpected keyword argument 'columns'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-9-913789c7326c> in <module>()
----> 1 ddf['result'] = ddf.map_partitions(test_f, columns=['col_1', 'col_2']).compute(get=get)
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\core.py in map_partitions(self, func, *args, **kwargs)
469 >>> ddf.map_partitions(func).clear_divisions() # doctest: +SKIP
470 """
--> 471 return map_partitions(func, self, *args, **kwargs)
472
473 @insert_meta_param_description(pad=12)
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\core.py in map_partitions(func, *args, **kwargs)
3163
3164 if meta is no_default:
-> 3165 meta = _emulate(func, *args, **kwargs)
3166
3167 if all(isinstance(arg, Scalar) for arg in args):
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\core.py in _emulate(func, *args, **kwargs)
3129 """
3130 with raise_on_meta_error(funcname(func)):
-> 3131 return func(*_extract_meta(args, True), **_extract_meta(kwargs, True))
3132
3133
~\AppData\Local\conda\conda\envs\tensorflow\lib\contextlib.py in __exit__(self, type, value, traceback)
75 value = type()
76 try:
---> 77 self.gen.throw(type, value, traceback)
78 except StopIteration as exc:
79 # Suppress StopIteration *unless* it's the same exception that
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\utils.py in raise_on_meta_error(funcname)
148 ).format(" in `{0}`".format(funcname) if funcname else "",
149 repr(e), tb)
--> 150 raise ValueError(msg)
151
152
ValueError: Metadata inference failed in `test_f`.
Original error is below:
------------------------
TypeError("test_f() got an unexpected keyword argument 'columns'",)
Traceback:
---------
File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\utils.py", line 137, in raise_on_meta_error
yield
File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\dask\dataframe\core.py", line 3131, in _emulate
return func(*_extract_meta(args, True), **_extract_meta(kwargs, True))
最佳答案
map_partitions
docs中有一个例子准确地实现正在尝试做的事情:
ddf.map_partitions(lambda df: df.assign(z=df.x * df.y))
当您调用 map_partitions
时(就像您在 pandas.DataFrame
上调用 .apply()
时),您尝试调用的函数map
(或apply
)将被赋予数据帧作为第一个参数。
在 dask.dataframe.map_partitions
的情况下,第一个参数将是分区,在 pandas.DataFrame.apply
的情况下 - a整个数据框。
这意味着您的函数必须接受数据帧(分区)作为第一个参数,并且在您的情况下可能如下所示:
def test_f(df, col_1, col_2):
return df.assign(result=df[col_1] * df[col_2])
请注意,在您调用 .compute()
之前,在这种情况下会发生(即安排发生)新列的分配。
在您的示例中,您在调用 .compute()
之后分配了列,这违背了使用 dask 的目的。 IE。在您调用 .compute()
之后,该操作的结果将被加载到内存中 如果有足够的空间 用于这些结果(如果没有,您只会得到 MemoryError
).
因此,为了您的工作示例,您可以:
1) 使用函数(以列名作为参数):
def test_f(df, col_1, col_2):
return df.assign(result=df[col_1] * df[col_2])
ddf_out = ddf.map_partitions(test_f, 'col_1', 'col_2')
# Here is good place to do something with BIG ddf_out dataframe before calling .compute()
result = ddf_out.compute(get=get) # Will load the whole dataframe into memory
2) 使用 lambda
(在函数中硬编码列名):
ddf_out = ddf.map_partitions(lambda df: df.assign(result=df.col_1 * df.col_2))
# Here is good place to do something with BIG ddf_out dataframe before calling .compute()
result = ddf_out.compute(get=get) # Will load the whole dataframe into memory
更新:
要逐行应用函数,这里引用您链接的帖子:
map
/apply
You can map a function row-wise across a series with
map
df.mycolumn.map(func)
You can map a function row-wise across a dataframe with
apply
df.apply(func, axis=1)
即对于您问题中的示例函数,它可能如下所示:
def test_f(dds, col_1, col_2):
return dds[col_1] * dds[col_2]
由于您将逐行应用它,因此函数的第一个参数将是一个系列(即数据框的每一行都是一个系列)。
要应用这个函数,你可以这样调用它:
dds_out = ddf.apply(
test_f,
args=('col_1', 'col_2'),
axis=1,
meta=('result', int)
).compute(get=get)
这将返回一个名为 'result'
的系列。
我想你也可以在每个分区上调用 .apply
一个函数,但它看起来并不比直接在数据帧上调用 .apply
更有效。但也许您的测试会证明并非如此。
关于python - 简单的 dask map_partitions 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47125665/
如果我有一个依赖于某些全局或其他常量的函数,如下所示: x = 123 def f(partition): return partition + x # note that x is def
我们可以通过哪些方式在 Dask Arrays 中执行项目分配?即使是一个非常简单的项目分配,如:a[0] = 2 不起作用。 最佳答案 正确的。这是文档中提到的第一个限制。 通常,涉及 for 循环
[mapr@impetus-i0057 latest_code_deepak]$ dask-worker 172.26.32.37:8786 distributed.nanny - INFO -
我正在构建一个 FastAPI 应用程序,它将为 Dask 数组的 block 提供服务。我想利用 FastAPI's asynchronous functionality旁边Dask-distrib
在延迟数据帧处理的几个阶段之后,我需要在保存数据帧之前对其进行重新分区。但是,.repartition() 方法要求我知道分区的数量(而不是分区的大小),这取决于处理后数据的大小,这是未知的。 我想我
我正在努力转换 dask.bag将字典放入 dask.delayed pandas.DataFrames进入决赛 dask.dataframe 我有一个函数 (make_dict) 将文件读入一个相当
我正在尝试使用 dask_cudf/dask 读取单个大型 parquet 文件(大小 > gpu_size),但它目前正在读取它到一个分区中,我猜这是从文档字符串推断出的预期行为: dask.dat
当启动一个 dask 分布式本地集群时,您可以为 dashboard_address 设置一个随机端口或地址。 如果稍后获取scheduler对象。有没有办法提取仪表板的地址。 我有这个: clust
我有一个 dask 数据框,由 parquet 支持。它有 1.31 亿行,当我对整个帧执行一些基本操作时,它们需要几分钟。 df = dd.read_parquet('data_*.pqt') un
我正在使用 24 个 vCPU 的谷歌云计算实例。运行代码如下 import dask.dataframe as dd from distributed import Client client =
我正在尝试在多台机器上分发一个大型 Dask 数据帧,以便(稍后)在数据帧上进行分布式计算。我为此使用了 dask-distributed。 我看到的所有 dask 分布式示例/文档都是从网络资源(h
我在 Django 服务器后面使用 Dask,这里总结了我的基本设置:https://github.com/MoonVision/django-dask-demo/可以在这里找到 Dask 客户端:h
我有以下格式的 Dask DataFrame: date hour device param value 20190701 21 dev_01 att_1 0.00
我正在尝试使用 dask 而不是 Pandas,因为我有 2.6gb csv 文件。 我加载它,我想删除一列。但似乎无论是 drop 方法 df.drop('column') 或切片 df[ : ,
我有一个比我的内存大得多的文本文件。我想按字典顺序对该文件的行进行排序。我知道如何手动完成: 分成适合内存的块 对块进行排序 合并块 我想用 dask 来做。我认为处理大量数据将是 dask 的一个用
使用 Dask 的分布式调度程序时,我有一个正在远程工作人员上运行的任务,我想停止该任务。 我该如何阻止?我知道取消方法,但如果任务已经开始执行,这似乎不起作用。 最佳答案 如果它还没有运行 如果任务
我需要将一个非常大的 dask.bag 的元素提交到一个非线程安全的存储区,即我需要类似的东西 for x in dbag: store.add(x) 我无法使用compute,因为包太大,无
如果我有一个已经索引的 Dask 数据框 >>> A.divisions (None, None) >>> A.npartitions 1 我想设置分区,到目前为止我正在做 A.reset_index
根据 this回答,如果 Dask 知道数据帧的索引已排序,则 Dask 数据帧可以执行智能索引。 如果索引已排序,我如何让 Dask 知道? 在我的具体情况下,我正在做这样的事情: for sour
我想从具有特定数量的工作人员的 python 启动本地集群,然后将客户端连接到它。 cluster = LocalCluster(n_workers=8, ip='127.0.0.1') client
我是一名优秀的程序员,十分优秀!