【问题标题】:Converting numpy array into dask dataframe column?将 numpy 数组转换为 dask 数据框列?
【发布时间】:2019-12-27 15:34:58
【问题描述】:

我有一个 numpy 数组,我想将它作为列添加到现有的 dask 数据框中。

enc = LabelEncoder()
nparr = enc.fit_transform(X[['url']])

我有 dask 数据框类型的 ddf。

ddf['nurl'] = nparr   ???

请问有什么优雅的方法可以实现上述目标吗?

Python PANDAS: Converting from pandas/numpy to dask dataframe/array 这并不能解决我的问题,因为我希望将 numpy 数组放入现有的 dask 数据帧中。

【问题讨论】:

标签: python numpy dask numpy-ndarray


【解决方案1】:

您可以将 numpy 数组转换为 dask Series 对象,然后将其合并到数据框。您将需要使用 Series 对象的 .to_frame() 方法,因为它只支持将数据帧与其他数据帧合并。

import dask.dataframe as dd
import numpy as np
import pandas as pd

df = pd.DataFrame({'x': range(30), 'y': range(0,300, 10)})
arr = np.random.randint(0, 100, size=30)

# create dask frame and series
ddf = ddf = dd.from_pandas(df, npartitions=5)
darr = dd.from_array(arr)
# give it a name to use as a column head
darr.name = 'z'

ddf2 = ddf.merge(darr.to_frame())

ddf2
# returns:
Dask DataFrame Structure:
                   x      y      z
npartitions=5
0              int64  int64  int32
6                ...    ...    ...
...              ...    ...    ...
24               ...    ...    ...
29               ...    ...    ...
Dask Name: join-indexed, 33 tasks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 2021-10-29
    • 2020-07-28
    • 2017-01-27
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多