目录
.withColumnRenamed 重命名列名,得到新的df
Column.astype(dataType) 和.cast (dataType)# 类型转换
column.asc 整个df按照某列的升序排序,常结合df.orderBy使用
Column.between(lowerBound, upperBound) 某字段是否在指定区间范围内
Column.contains(other) # 是否包含某个字符,直接返回的是列,用filter或者[]筛选出得到对应的df行即可。
Column.endswith(other) # 字段以什么结束的值,直接返回的是列,用filter或者[]筛选出得到对应的df行即可。
Column.isNotNull() # 筛选列中非空的,得到对应的内容
Column.isin(*cols) # 返回包含某些值的行
Column.like(other) # 返回含有关键词的行, rlike 会进行正则匹配,
如果你觉得下面的资料有用,还请点赞、收藏,支持下,你的鼓励是我继续整理的一个动力,非常感谢
样例数据,简单建一个DataFrame
rdd = sc.parallelize([("Sam", 28, 88.52, "M"),
("Flora", 28, 90.55, "F"),
("Mey", 1, None, "M"),
("Chery", 7, 80.23, "F")])
test = rdd.toDF(["name", "age", "score", "sex"])
test.show()
+-----+---+-----+---+ | name|age|score|sex| +-----+---+-----+---+ | Sam| 28|88.52| M| |Flora| 28|90.55| F| | Mey| 1| null| M| |Chery| 7|80.23| F|
.withColumn 新增一列
新增列,注意原dataframe并未改变
test2 = test.withColumn('big_score',test['score']+1)
test2.show()
结果显示:
+-----+---+-----+---+---------+ | name|age|score|sex|big_score| +-----+---+-----+---+---------+ | Sam| 28|88.52| M| 89.52| |Flora| 28|90.55| F| 91.55| | Mey| 1| null| M| null| |Chery| 7|80.23| F| 81.23| +-----+---+-----+---+---------+
1)新增一列常数项 withColumn 结合 functions.lit(value)
from pyspark.sql import functions
test2 = test.withColumn("add_constant",functions.lit(10))
test2.show()
结果如:
+-----+---+-----+---+------------+ | name|age|score|sex|add_constant| +-----+---+-----+---+------------+ | Sam| 28|88.52| M| 10| |Flora| 28|90.55| F| 10| | Mey| 1| null| M| 10| |Chery| 7|80.23| F| 10| +-----+---+-----+---+------------+
2) 简单根据某列进行计算得到新的列
from pyspark.sql import functions
test_3 = test.withColumn("name_length",functions.length(test.name))
test_3.show()
结果如:
+-----+---+-----+---+-----------+ | name|age|score|sex|name_length| +-----+---+-----+---+-----------+ | Sam| 28|88.52| M| 3| |Flora| 28|90.55| F| 5| | Mey| 1| null| M| 3| |Chery| 7|80.23| F| 5|
3)使用selectExpr 里面的sql计算
test_4 = test.selectExpr(["name","age","score","sex","length(name) as name_length"])
test_4.show()
结果如:
+-----+---+-----+---+-----------+ | name|age|score|sex|name_length| +-----+---+-----+---+-----------+ | Sam| 28|88.52| M| 3| |Flora| 28|90.55| F| 5| | Mey| 1| null| M| 3| |Chery| 7|80.23| F| 5| 此处参考: pyspark 给dataframe增加新的一列
.drop丢弃指定列
删除列,返回一个新的dataframe,注意原dataframe的列并未改变。如果要改变原df,需要赋值覆盖。
test.drop('age').show() # 得到的新的df删除了列
print(test.show()) # 原df中age仍然存在。
test= test.drop('age')
test.show() # age被删除
.alias重命名列名的别名
输入列的操作,在select等里面嵌套着用
test.select('name',test.age.alias('gender')).show()
## test本身的列age并没有改变
输出:
+-----+------+ | name|gender| +-----+------+ | Sam| 28| |Flora| 28| | Mey| 1| |Chery| 7| +-----+------+

本文介绍了 PySpark 中 DataFrame 的常用操作方法,包括新增列、删除列、重命名列、缺失值填充、值替换、类型转换及排序等。通过具体实例展示了如何高效地处理数据。
最低0.47元/天 解锁文章
3306

被折叠的 条评论
为什么被折叠?



