我有一个数据框架,看起来像这样:
| id | c1 | c2 | c3 |
|------|-----|------|-------|
| 1334 | 20 | 3565 | 0.005 |
| 1335 | 543 | 2100 | 0.205 |
c3
由c1 / (c1 + c2)
计算,如下所示:
agg = (
df1
.groupby('id')
.agg(
F.count('c1').alias('c1'),
F.count('c2').alias('c2')
)
).withColumn('c3',
F.col('c1') / (F.col('c1') + F.col('c2')))
我想有条件地改变我的.withColumn
的值,像这样:
if c1 < 50 then 0
if c2 > 1000 then 1000
对于id
1334,计算结果为0 / (0 + 1000)
,对于id
1335,计算结果为545 / (543 + 1000)
。
我曾尝试使用.when()
,但似乎无法获得语法正确
你可以试试:
.withColumn(
'c3',
F.when(F.col('c1') < 50, 0).otherwise(F.col('c1')) / (
F.when(F.col('c1') < 50, 0).otherwise(F.col('c1')) +
F.when(F.col('c2') > 1000, 1000).otherwise(F.col('c2'))
)
)