[英]How to create a function that checks if one row in a PySpark column of a dataframe matches another row in the same column of another dataframe?
[英]How to Set Pyspark Dataframe Headers to another Row?
我有一个看起来像这样的数据框:
# +----+------+---------+
# |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来读取它
你试过这个吗? 标题=真
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.getOrCreate()
df = spark.read.csv("TSCAINV_062020.csv",header=True)
如果标题未设置为 True,Pyspark 会将列名称设置为 _c0、_c1、_c2,并将列向下推一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.