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

查看:145
本文介绍了根据条件将列添加到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,则为Yes,否则为No.

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天全站免登陆