【Pyspark】Dataframe添加新的一列

1. lit 添加常量 字符串

若需要添加一列固定值,比如地名、邮编、标号、字符串之类的,可以直接使用lit 添加常量

Eg: 添加字符串

import pyspark.sql.functions as F

d7=d61.withColumn('line_results',F.lit(string_line))

Eg: 添加常量10

from pyspark.sql.functions import lit

df.withColumn('new_column', lit(10))

 

2. withColumn + UDF 添加函数处理后的结果

另一种方法是利用UDF(user defined function)模块。

 

通过UDF函数对输入进行处理后,将输出添加到原始df中

eg :

df_spark_route_info.withColumn("route_detail_new",rearrange_routedetail(df["list_string"]))

其中,rearrange_routedetail为定义好的udf函数,输入为df["list_string"], 处理后输出为route_detail_new,并以route_detail_new为列名被添加在df_spark_route_info 中

 

eg:

https://www.jianshu.com/p/0a5d7ca2b575

https://www.jianshu.com/p/bded081b5350

除了withColumn方法,还可以利用spark的udf模块添加新的列。在本例中,还需要添加相应的时间列,此时withColumn方法并不适用,需要导入udf方法,该方法有两个参数,分别为自定义的函数名及返回值类型。

global idx
idx = 0
date = gettime()
def set_date(x):
    global idx  # 将idx设置为全局变量
    if x is not None:
        idx += 1
        return date[idx - 1]
index = udf(set_date, StringType())
yHat = yHat.withColumn("date", index(yHat["pm25"]))

 

3. withColumn 添加简单加减乘除等结果

https://www.jianshu.com/p/0a5d7ca2b575

常见的一种方法是调用dataframe的方法,但是该方法存在一定的限制,即新添加的列只能根据现有列转换 eg 加减乘除 得到;

Eg:

yHat = yHat.withColumn("pm25", yHat["pm25"]*(maxValue - minValue) + minValue)
yHat = yHat.withColumn("pm10", yHat["pm25"] + 10)
yHat = yHat.withColumn("CO", yHat["pm25"] + 20)
yHat = yHat.withColumn("NO2", yHat["pm25"] + 30)
yHat = yHat.withColumn("NO", yHat["pm25"] + 40)
yHat = yHat.withColumn("SO2", yHat["pm25"] + 50)

 

其只能根据已经存在的列添加, 不好用

https://codeday.me/bug/20180127/122213.html

 

 

引申:

pyspark合并/竖直拼接行、列

https://blog.csdn.net/yepeng2007fei/article/details/78645329

合并列:

df.withColumn(新列名,df[列名])   #将df中的列合并到df中

行合并:

df.union(df1)   #将df与df1进行行合并,这时df与df1的列名要相同

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值