2

我是考拉的新手。我被告知在我的工作中使用考拉而不是熊猫。早些时候,当我们有数据框时,我们将其转换为 pandas 并将其用于 np.where 并在内部进行条件检查。在 pandas 中我们曾经做过 np.where(condition,action1,action2) 的例子。当我尝试使用考拉做同样的事情时,我们会在下面收到错误

“PandasNotImplementedError:该方法pd.Series.__iter__()未实现。如果要将数据收集为 NumPy 数组,请改用 'to_numpy()'。”

我什至尝试了 ks.series 和 ks.dataframe 但错误没有消失。

考拉中是否有任何方法/函数可以接受 3 个参数(条件、动作1、动作2),就像我们在熊猫中使用 np.where 一样。如果有人也通过示例进行解释,那将非常有帮助。

4

1 回答 1

1

一个可能的解决方案类似于np.where自己创建一个使用 koalas' 的函数(如下所示)where

import databricks.koalas as ks


# sample dataframe
df = ks.DataFrame({
  'id': [1, 2, 3, 4, 5],
  'cost': [5000, 4000, 3000, 4500, 2000],
  'class': ['A', 'A', 'B', 'C', 'A']
})


# your custom function
def numpy_where(s, cond, action1, action2):
  return s.where(cond, action2).where(~cond, action1)


# create sample new column
df['new_col'] = numpy_where(df['class'], df['class'] == 'A', 'yes', 'no')
print(df)
#    id  cost class new_col
# 0   1  5000     A     yes
# 1   2  4000     A     yes
# 2   3  3000     B      no
# 3   4  4500     C      no
# 4   5  2000     A     yes

基本上:

  • sks.Series你计算的地方
  • cond是要满足的条件
  • action1cond为真时要插入的值
  • action2cond为 false时要插入的值
于 2021-12-30T11:19:27.600 回答