使用考拉代替 pandas
Use of koalas instead of pandas
我是考拉新手。我被告知在我的工作中使用 koalas 而不是 pandas。
早些时候,当我们有数据帧时,我们将其转换为 pandas 并将其用于 np.where 并在内部进行条件检查。 pandas 中的示例我们过去常常这样做
np.where(条件、动作 1、动作 2)。
当我尝试使用 koalas 时,我们得到以下错误
“PandasNotImplementedError:方法 pd.Series.__iter__()
未实现。如果您想将数据收集为 NumPy 数组,请改用 'to_numpy()'。”
我什至尝试了 ks.series 和 ks.dataframe 但错误并没有出现。
考拉中有没有像我们在pandas中使用np.where一样接受3个参数(条件,action1,action2)的method/function。如果有人也通过示例进行解释,那将会很有帮助。
类似于np.where
的可能解决方案是自己创建一个函数(如下所示),它使用考拉的 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
基本上:
s
是您计算 where 的 ks.Series
cond
是要满足的条件
action1
是当cond
为真 时要插入的值
action2
是cond
为false时要插入的值
我是考拉新手。我被告知在我的工作中使用 koalas 而不是 pandas。 早些时候,当我们有数据帧时,我们将其转换为 pandas 并将其用于 np.where 并在内部进行条件检查。 pandas 中的示例我们过去常常这样做 np.where(条件、动作 1、动作 2)。 当我尝试使用 koalas 时,我们得到以下错误
“PandasNotImplementedError:方法 pd.Series.__iter__()
未实现。如果您想将数据收集为 NumPy 数组,请改用 'to_numpy()'。”
我什至尝试了 ks.series 和 ks.dataframe 但错误并没有出现。
考拉中有没有像我们在pandas中使用np.where一样接受3个参数(条件,action1,action2)的method/function。如果有人也通过示例进行解释,那将会很有帮助。
类似于np.where
的可能解决方案是自己创建一个函数(如下所示),它使用考拉的 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
基本上:
s
是您计算 where 的 cond
是要满足的条件action1
是当cond
为真 时要插入的值
action2
是cond
为false时要插入的值
ks.Series