根据条件将列添加到 pyspark 数据框 [英] Add column to pyspark dataframe based on a condition

查看:35
本文介绍了根据条件将列添加到 pyspark 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 data.csv 文件包含三列,如下所示.我已将此文件转换为 python spark 数据帧.

My data.csv file has three columns like given below. I have converted this file to python spark dataframe.

  A   B    C
| 1 | -3 | 4 |
| 2 | 0  | 5 |
| 6 | 6  | 6 |

我想在 spark 数据框中添加另一列 D,其值为 Yes 或 No,条件是如果 B 列中的相应值大于 0,则是,否则为否.

I want to add another column D in spark dataframe with values as Yes or No based on the condition that if corresponding value in B column is greater than 0 then yes otherwise No.

  A   B    C   D
| 1 | -3 | 4 | No  |
| 2 | 0  | 5 | No  |
| 6 | 6  | 6 | Yes |

我无法通过 PySpark 数据帧操作来实现这一点.

I am not able to implement this through PySpark dataframe operations.

推荐答案

试试这个:

from pyspark.sql import functions as f
df.withColumn('D', f.when(f.col('B') > 0, "Yes").otherwise("No")).show()

这篇关于根据条件将列添加到 pyspark 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆