python - 如何将 Pyspark 数据框标头设置为另一行?
问题描述
我有一个看起来像这样的数据框:
# +----+------+---------+
# |col1| col2 | col3 |
# +----+------+---------+
# | id| name | val |
# | 1 | a01 | X |
# | 2 | a02 | Y |
# +---+-------+---------+
我需要从中创建一个新的数据框,使用 row[1] 作为新的列标题并忽略或删除 col1、col2 等行。新表应如下所示:
# +----+------+---------+
# | id | name | val |
# +----+------+---------+
# | 1 | a01 | X |
# | 2 | a02 | Y |
# +---+-------+---------+
列可以是可变的,因此我不能使用名称在新数据框中显式设置它们。这不使用熊猫df。
解决方案
id
假设在 col1、name
col2和val
col3中只有一行,您可以使用以下逻辑(为了清晰和解释而注释)
#select the row with the header name
header = df.filter((df['col1'] == 'id') & (df['col2'] == 'name') & (df['col3'] == 'val'))
#selecting the rest of the rows except the first one
restDF = df.subtract(header)
#converting the header row into Row
headerColumn = header.first()
#looping columns for renaming
for column in restDF.columns:
restDF = restDF.withColumnRenamed(column, headerColumn[column])
restDF.show(truncate=False)
这应该给你
+---+----+---+
|id |name|val|
+---+----+---+
|1 |a01 |X |
|2 |a02 |Y |
+---+----+---+
但是最好的选择是在使用sqlContext从源代码读取数据帧时,将header 选项设置为 true来读取它
推荐阅读
- haskell - 使用类型类约束快速检查并报告生成的值?
- javascript - Angular 应用程序未在 IE 浏览器中打开,而应用程序在 Chrome 中打开
- node.js - Web 应用程序如何通过文本文件与不同系统进行通信?
- c# - 抽象出两个几乎相同的方法,它们的区别仅在于它们在对象列表上使用的属性
- java - MockMvc 无法使用参数 @DateValid 进行验证
- c# - 如何知道 Last Window-Startup-Location 刚刚关闭的时间?WPF 应用程序
- mysql - 从 MySql 工作台中的现有列创建具有条件值的新列?
- reactjs - Formik Material UI 和 react 测试库
- json - 如何修复api json删除请求
- ios - 由于 NSLayoutConstraint 错误,具有 automaticDimension 的 UITableView 不会动态增加大小