这是对dash洗改数据的跟进问题。
我有一个现有的dask数据框df,希望在其中执行以下操作:
df['rand_index'] = np.random.permutation(len(df))
Run Code Online (Sandbox Code Playgroud)
但是,这会产生错误Column assignment doesn't support type ndarray。我试图使用df.assign(rand_index = np.random.permutation(len(df))它给出相同的错误。
这是一个最小的(不是)工作示例:
import pandas as pd
import dask.dataframe as dd
import numpy as np
df = dd.from_pandas(pd.DataFrame({'A':[1,2,3]*10, 'B':[3,2,1]*10}), npartitions=10)
df['rand_index'] = np.random.permutation(len(df))
Run Code Online (Sandbox Code Playgroud)
前面的问题提到了使用,df = df.map_partitions(add_random_column_to_pandas_dataframe, ...)但是我不确定这是否与该特定情况有关。
我尝试过
df['rand_index'] = dd.from_array(np.random.permutation(len_df)),执行没有问题。当我检查时df.head(),似乎已经创建了新列。但是,当我看时df.tail(),rand_index是一堆NaNs。
实际上,只是为了确认我检查了df.rand_index.max().compute()哪个结果小于len(df)-1。所以这可能df.map_partitions是发挥作用的地方,因为我怀疑这是将dask分区的问题。在我的特定情况下,我有80个分区(不涉及示例情况)。
您需要将np.random.permutation(len(df))dask理解为以下类型:
permutations = dd.from_array(np.random.permutation(len(df)))
df['rand_index'] = permutations
df
Run Code Online (Sandbox Code Playgroud)
这将产生:
Dask DataFrame Structure:
A B rand_index
npartitions=10
0 int64 int64 int32
3 ... ... ...
... ... ... ...
27 ... ... ...
29 ... ... ...
Dask Name: assign, 61 tasks
Run Code Online (Sandbox Code Playgroud)
因此,现在要由您决定是否要.compute()计算实际结果。
| 归档时间: |
|
| 查看次数: |
3982 次 |
| 最近记录: |