How to change column name of a dataframe with respect to other dataframe

假如想象 提交于 2019-12-11 08:54:47

问题


I have a requirement to change column name of a dataframe df with respect to other dataframe df_col using pyspark

df

+----+---+----+----+
|code| id|name|work|
+----+---+----+----+
| ASD|101|John| DEV|
| klj|102| ben|prod|
+----+---+----+----+

df_col

+-----------+-----------+
|col_current|col_updated|
+-----------+-----------+
|         id|     Row_id|
|       name|       Name|
|       code|   Row_code|
|       Work|  Work_Code|
+-----------+-----------+

if df column matches col_current, df column should replace with col_updated. ex: if df.id matches df.col_current, df.id should replace with Row_id.

expected output

Row_id,Name,Row_code,Work_code
101,John,ASD,DEV
102,ben,klj,prod

Note: I want this process to be dynamic.


回答1:


Just collect the df_col as dictionary:

df = spark.createDataFrame(
    [("ASD", "101" "John", "DEV"), ("klj","102", "ben", "prod")],
    ("code", "id", "name", "work")
)

df_col = spark.createDataFrame(
    [("id", "Row_id"), ("name", "Name"), ("code", "Row_code"), ("Work", "Work_Code")],
    ("col_current", "col_updated")
)

name_dict = df_col.rdd.collectAsMap()

and use select with list comprehension:

df.select([df[c].alias(name_dict.get(c, c)) for c in df.columns]).printSchema()
# root
#  |-- Row_code: string (nullable = true)
#  |-- Row_id: string (nullable = true)
#  |-- Name: string (nullable = true)
#  |-- work: string (nullable = true)

where name_dict is standard Python dictionary:

{'Work': 'Work_Code', 'code': 'Row_code', 'id': 'Row_id', 'name': 'Name'}

name_dict.get(c, c) gets new name, given current name, or current name if no match:

name_dict.get("code", "code")
# 'Row_code'

name_dict.get("work", "work")  # Case sensitive 
# 'work'

and alias just renames column (df[col]) to name returned from name_dict.get.



来源:https://stackoverflow.com/questions/48187400/how-to-change-column-name-of-a-dataframe-with-respect-to-other-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!