python - 如何根据 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
解决方案
when
您可以使用 with / otherwise
as复制这些就地分配:
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|
+----+-----+
推荐阅读
- grpc - 从源代码构建时 gRPC 失败
- php - Symfony 3.4 命令与 oracle 钱包 ORA-12154:TNS:无法解析指定的连接标识符
- excel - Excel 第 n 个最小的 DISTINCT 值
- sql - 将 Oracle SQL CLOB 值(>4000 个字符)移动到 SQL Server 而不进行修剪
- android - 在 SegmentedBarView-Android 中实现 onItemClickListener
- sql - 形成一个 Oracle SQL WHERE 语句以在输入“ALL”时包含所有结果或仅包含他们输入的条件
- openshift - 从 shell 在 Openshift 中创建 PostgreSQL 应用程序
- c# - 如何使用c#检查sql表中是否存在值,如果是则继续if
- ajax - 如何在 Yii2 中实现 ajax Tabs 和 Google Charts
- flutter - Flutter:TextEditingController 数组