繁体   English   中英

如何基于在PySpark中其他列中进行的计算来创建新列

[英]How to create a new column based on calculations made in other columns in PySpark

我有以下DataFrame:

+-----------+----------+----------+
|   some_id | one_col  | other_col|
+-----------+----------+----------+
|       xx1 |        11|       177|         
|       xx2 |      1613|      2000|    
|       xx4 |         0|     12473|      
+-----------+----------+----------+

我需要添加一个新列,该列基于在第一列和第二列上进行的一些计算,例如,对于col1_value = 1和col2_value = 10将需要产生col1包含在col2中的百分比,因此col3_value =(1/10)* 100 = 10%:

+-----------+----------+----------+--------------+
|   some_id | one_col  | other_col|  percentage  |
+-----------+----------+----------+--------------+
|       xx1 |        11|       177|     6.2      |  
|       xx3 |         1|       10 |      10      |     
|       xx2 |      1613|      2000|     80.6     |
|       xx4 |         0|     12473|      0       |
+-----------+----------+----------+--------------+

我知道我需要为此使用udf,但是如何基于结果直接添加新的列值?

一些伪代码:

import pyspark
from pyspark.sql.functions import udf

df = load_my_df

def my_udf(val1, val2):
    return (val1/val2)*100

udf_percentage = udf(my_udf, FloatType())

df = df.withColumn('percentage', udf_percentage(# how?))

谢谢!

df.withColumn('percentage', udf_percentage("one_col", "other_col"))

要么

df.withColumn('percentage', udf_percentage(df["one_col"], df["other_col"]))

要么

df.withColumn('percentage', udf_percentage(df.one_col, df.other_col))

要么

from pyspark.sql.functions import col

df.withColumn('percentage', udf_percentage(col("one_col"), col("other_col")))

但是为什么不只是:

df.withColumn('percentage', col("one_col") / col("other_col") * 100)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM