任务项目分配。不能使用 loc 进行项目分配

Dask item assignment. Cannot use loc for item assignment

我有一个 parquet 文件文件夹,我无法将其放入内存,因此我使用 dask 来执行数据清理操作。我有一个功能,我想在其中执行项目分配,但我似乎无法在网上找到任何符合此特定功能解决方案的解决方案。下面是在 pandas 中工作的函数。如何在 dask 数据框中获得相同的结果?我认为延迟可能会有所帮助,但我尝试编写的所有解决方案都没有奏效。

def item_assignment(df):

    new_col = np.bitwise_and(df['OtherCol'], 0b110)

    df['NewCol'] = 0
    df.loc[new_col == 0b010, 'NewCol'] = 1
    df.loc[new_col == 0b100, 'NewCol'] = -1 

    return df

TypeError: '_LocIndexer' object does not support item assignment

在这种情况下,您可以使用 map_partitions,您可以使用原始 pandas 功能。即

ddf.map_partitions(item_assignment)

这对 dask 数据帧的单个 pandas 个组成数据帧进行操作

df = pd.DataFrame({"OtherCol":[0b010, 0b110, 0b100, 0b110, 0b100, 0b010]})
ddf = dd.from_pandas(df, npartitions=2)
ddf.map_partitions(item_assignment).compute()

我们看到了预期的结果:

   OtherCol  NewCol
0         2       1
1         6       0
2         4      -1
3         6       0
4         4      -1
5         2       1

您可以将 loc 作业替换为 dask.dataframe.Series.mask:

df['NewCol'] = 0
df['NewCol'] = df['NewCol'].mask(new_col == 0b010, 1)
df['NewCol'] = df['NewCol'].mask(new_col == 0b100, -1)