首页 > 解决方案 > 如何根据 PySpark 中的条件修改行的子集

问题描述

我尝试将所有 MPa 值转换为 Pa。我在 pandas 中使用的代码如下所示。我如何将其翻译成 pyspark?

file_df.loc[file_df['Unit'] == 'MPa', 'Value'] = file_df['Value'] * 1000000 #coverts Value to Pa from MPa
file_df.loc[file_df['Unit'] == 'MPa', 'Unit'] = 'Pa' # replace the MPa with Pa

标签: pythonpandaspyspark

解决方案


when您可以使用 with / otherwiseas复制这些就地分配:

from pyspark.sql.functions import when, col, lit

m = sparkdf.Unit == 'MPa'
(sparkdf.withColumn("Value", when(m, col('Value')*1000).otherwise(col('Value')))
        .withColumn("Unit",  when(m, lit('Pa')).otherwise(col('Unit'))))

小工作示例:

df = pd.DataFrame({'Unit':['MPa', 'MPb', 'MPc'],
                   'Value':[5, 4, 3]})

sparkdf = spark.createDataFrame(df)
m = sparkdf.Unit == 'MPa'

(sparkdf.withColumn("Value",  when(m, col('Value')*1000).otherwise(col('Value')))
        .withColumn("Unit",  when(m, lit('Pa')).otherwise(col('Unit')))).show()

+----+-----+
|Unit|Value|
+----+-----+
|  Pa| 5000|
| MPb|    4|
| MPc|    3|
+----+-----+

推荐阅读