使用函数将值应用于 Dask 数据帧映射

时间:2021-05-25 02:48:43

标签: python pandas dask dask-distributed

在下面的 Dask 代码中,我试图根据函数 apply_masks 中的逻辑设置数据帧字段的值:

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

def apply_masks(df):
   if df['Age'] > 14:
       df['outcol'] = 6
   else:
       df['outcol'] = 5
   return df

data = [[1,100, 12, 6], [1,200, 18, 5], [1,170, 22, 4]]
df = pd.DataFrame(data, columns = ['outcol', 'Weight', 'Age', 'Height']) 
ddf = daskDataFrame.from_pandas(df, npartitions=100)
ddf = ddf.map_partitions(apply_masks)
print(ddf.compute())

问题是得到一个异常:

<块引用>

ValueError:元数据推断在 apply_masks 中失败。

您提供了自定义函数,Dask 无法确定 该函数返回的输出类型。

要解决此问题,请提供 meta= 关键字。的文档字符串 您运行的 Dask 函数应该有更多信息。

原始错误如下: ------------------------ ValueError('Series 的真值不明确。使用 a.empty, a.bool(), a.item ()、a.any() 或 a.all().')

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

试试 assign + np.where

def apply_masks(df):
    return df.assign(outcol=np.where(df['Age'] > 14, 6, 5))

结果:

   outcol  Weight  Age  Height
0       5     100   12       6
1       6     200   18       5
2       6     170   22       4
相关问题