我有一个如下所示的数据框:
# +----+------+---------+
# |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 |
# +---+-------+---------+
列可以是可变的,因此我无法使用名称在新数据框中显式设置它们。这不是使用 pandas df 的。
假设只有一行id
in col1, name
in col2 and val
in 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 |
+---+----+---+
但最好的选择是阅读它标头选项设置为 true在阅读时数据框 using sql上下文从源头
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)