在带有列表元素的pandas表上使用dask中的map_partitions和power函数时出现问题

问题描述 投票:0回答:1

我使用 Dask 框架开发了以下 Python 代码:

# Create a Pandas DataFrame
df = pd.DataFrame({
    'A': [[1], [2], [3], [4], [5]],
    'B': [[6], [7], [8], [9], [10]]
})

# Convert the Pandas DataFrame to a Dask DataFrame
ddf = dd.from_pandas(df, npartitions=2)

def my_function2(x):
    return x[0]**2

# Define a function to apply to each partition
def my_function(df):
    return df.map(my_function2)

# Apply the function to each partition of the Dask DataFrame
result = ddf.map_partitions(my_function).compute()

当我执行它时出现以下错误:

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

这是我的代码的简短版本。它本质上对 pandas 表中的浮点数应用幂运算符,该浮点数作为列表存储在表的每个单元格中。导致此错误的原因可能是什么?我尝试了

np.power(x[0])
x[0]*x[0]
而不是
x[0]**2

python dask
1个回答
0
投票

错误是在 dask 尝试猜测 map_partitions 的结果类型时发生的。它使用列的虚拟值而不是潜在的大数据框,并且您的列表为列提供“列表”类型。由于“对象”类型列中最常见的值是字符串,因此您会看到您看到的错误。

解决方案是告诉map_partitions你的期望。

result = ddf.map_partitions(my_function, meta=pd.DataFrame({"A": [0], "B": [0]})).compute()
© www.soinside.com 2019 - 2024. All rights reserved.