【问题标题】:How to convert np.where() while converting pandas to koalas?如何在将熊猫转换为考拉的同时转换 np.where()?
【发布时间】:2021-12-28 17:39:00
【问题描述】:

我正在将一些熊猫系列和熊猫数据框转换为考拉以实现可扩展性。但是在我使用np.where() 的地方,我试图传递考拉数据帧,就像之前传递熊猫数据帧一样。但是我收到了一个错误 PandasNotImplementedError。

我该如何克服这个错误?我试过ks.where(),但没用。

这是我正在使用 pandas 编写的代码模型。

import pandas as pd
import numpy as np
pdf = np.where(condition, action1, action2)

如果我使用 toPandas()from_pandas() 将 koalas 转换回 pandas,代码就可以工作,但由于性能和可扩展性的原因,我不能使用 pandas。如果可能的话,请建议我在 Koalas 中使用一种替代方法,或者为 numpy 提供一个替代库,它可以很好地与 koalas 配合使用。

【问题讨论】:

标签: python pandas dataframe numpy spark-koalas


【解决方案1】:

我对考拉不太熟悉,但我认为使用DataFrame.where() 会起作用。

例如

from databricks.koalas.config import set_option, reset_option
set_option("compute.ops_on_diff_frames", True)
df1 = ks.DataFrame({'A': [0, 1, 2, 3, 4], 'B':[100, 200, 300, 400, 500]})
df2 = ks.DataFrame({'A': [0, -1, -2, -3, -4], 'B':[-100, -200, -300, -400, -500]})
df1.where(df1 > 1, df2)

如果你需要的话,还有一个对应的考拉 Series.where()。

【讨论】:

  • 我之前试过了。但是我得到了 TypeError : where() 需要 2 到 3 个位置参数,但给出了 4 个。
  • @FavazMusthafa 你试过给它更少的参数吗?
  • 我正在尝试将 pandas 中的现有逻辑转换为考拉。所以现有的代码是pdf=np.where(condition, arg1, arg2)。但是对于同样的条件考拉它只接受 kdf=kdf.where(condition, arg1)
  • @FavazMusthafa 这个想法是 arg1 是您现有的数据帧,它使用条件在现有数据帧和另一个数据帧 arg2 之间进行选择。它有同样多的参数,只是其中一个参数位于.where 之前。
【解决方案2】:

根据 Koalas (1.8.2) 上的 documentationdatabricks.koalas.DataFramedatabricks.koalas.Series 上的 where 函数在条件为 False 时仅接受两个参数,条件和值。只要条件是True,值就不会改变。它的行为类似于它在 Pandas 中的行为。

因此,可以像这样使用 where 语句的链接:

kdf.where(condition, action2).where(~condition, action1)
# action1 --> Action when condition is True.
# action2 --> Action when condition is False.

# The output of this cannot be assigned back to a column though. To assign the output to some column, the where has to be applied on a Series.
kdf['some_column'].where(condition, action2).where(~condition, action1)

另外,请注意,在 Koalas 上,databricks.koalas.Series 上的 where 条件可以分配回一列,但不能将 where 条件应用于 databricks.koalas.DataFrame 时的输出,就像在您的情况下可以在 Pandas 中完成的那样。

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2020-10-30
    • 2021-09-23
    • 2021-12-07
    • 2016-03-27
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多