Python 有条件地控制和中的值

Python 有条件地控制和中的值,python,apache-spark,pyspark,apache-spark-sql,Python,Apache Spark,Pyspark,Apache Spark Sql,我有一个数据框,看起来像这样: | id | c1 | c2 | c3 | |------|-----|------|-------| | 1334 | 20 | 3565 | 0.005 | | 1335 | 543 | 2100 | 0.205 | c3的计算方法如下: agg = ( df1 .groupby('id') .agg( F.count('c1').alias('c1'), F.count('c2').

我有一个数据框,看起来像这样:

| id   | c1  | c2   | c3    |
|------|-----|------|-------|
| 1334 | 20  | 3565 | 0.005 |
| 1335 | 543 | 2100 | 0.205 |
c3
的计算方法如下:

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')))
if c1 < 50 then 0
if c2 > 1000 then 1000
我想有条件地更改my
.withColumn
中的值,如下所示:

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')))
if c1 < 50 then 0
if c2 > 1000 then 1000
如果c1<50,则为0
如果c2>1000,则为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'))
    )
)
.withColumn(
“c3”,
当(F.col('c1')小于50,0时。否则(F.col('c1'))/(
当(F.col('c1')小于50,0)时,否则(F.col('c1'))+
当(F.col('c2')>10001000时。否则(F.col('c2'))
)
)
您可以尝试以下方法:

.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'))
    )
)
.withColumn(
“c3”,
当(F.col('c1')小于50,0时。否则(F.col('c1'))/(
当(F.col('c1')小于50,0)时,否则(F.col('c1'))+
当(F.col('c2')>10001000时。否则(F.col('c2'))
)
)