[英]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.