Spark DataFrame
don't have strict order so indexing is not meaningful. Instead we use SQL-like DSL. Here you'd use where
(filter
) and select
. If data looked like this:
import pandas as pd
import numpy as np
from pyspark.sql.functions import col, sum as sum_
np.random.seed(1)
df = pd.DataFrame({
c: np.random.randn(1000) for c in ["column_A", "column_B", "column_C"]
})
amount
would be
amount
# 0.9334143225687774
and Spark equivalent is:
sdf = spark.createDataFrame(df)
(amount_, ) = (sdf
.where(sdf.column_A > 0.0)
.select(sum_(sdf.column_B * sdf.column_C) / sum_(sdf.column_C))
.first())
and results are numerically equivalent:
abs(amount - amount_)
# 1.1102230246251565e-16
You could also use conditionals:
from pyspark.sql.functions import when
pred = col("column_A") > 0.0
amount_expr = sum_(
when(pred, col("column_B")) * when(pred, col("column_C"))
) / sum_(when(pred, col("column_C")))
sdf.select(amount_expr).first()[0]
# 0.9334143225687773
which look more Pandas-like, but are more verbose.