1

我正在将用 Pandas 编写的代码转换为 Koalas,但是在使用 numpy 时遇到了错误,其中:

import pandas as pd
import numpy as np
import databricks.koalas as ks

data = {'credit': [123.23, 23423.56, 0, 0], 'debit': [0, 0, 234.21, 95.32]}

df = ks.DataFrame(data)

df['flag'] = np.where(
    df['credit'] != '',
    'C',
    np.where(
        df['debit'] != '',
        'D',
        ''
    )
)

返回错误:

PandasNotImplementedError: The method `pd.Series.__iter__()` is not implemented. If you want to collect your data as an NumPy array, use 'to_numpy()' instead.

如果我尝试将 Koalas 数据帧转换为to_numpy()toPandas()保持代码不变,我就会耗尽内存。这段代码中有很多嵌套的 np.where() 语句,以及我非常不想重写的 numpy 的许多其他用途。

我不清楚是否有一种简单的方法可以np.where()使用考拉数据框将这些(或任何其他 numpy 语句)保留在代码中。

我知道有一种模拟np.where()使用的方法,df.assign(flag=())但我不清楚如何使用该方法来模拟嵌套条件。我的尝试如下:

# works but does not include the second condition
df = df.assign(flag= df.debit.apply(lambda x: "D" if x != "" else "")

# Does not work and returns an error
df = test_df.assign(flag= df.debit.apply(
  lambda x: "D" if x != "" else (
    df.credit.apply(
      lambda x: "C" if x != "" else ""))))

错误:PicklingError: Could not serialize object: TypeError: can't pickle _thread.RLock objects

4

0 回答 0