如何相对于其他数据框更改数据框的列名
How to change column name of a dataframe with respect to other dataframe
我需要使用 pyspark
更改数据框 df
相对于其他数据框 df_col
的列名
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|
+-----------+-----------+
如果 df 列匹配 col_current,df 列应替换为 col_updated。例如:如果 df.id 匹配 df.col_current,则 df.id 应替换为 Row_id。
预期输出
Row_id,Name,Row_code,Work_code
101,John,ASD,DEV
102,ben,klj,prod
注意:我希望这个过程是动态的。
只需收集 df_col
作为字典:
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()
并使用 select
和列表理解:
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)
其中 name_dict
是标准 Python 字典:
{'Work': 'Work_Code', 'code': 'Row_code', 'id': 'Row_id', 'name': 'Name'}
name_dict.get(c, c)
获取新名称、当前名称或当前名称(如果不匹配):
name_dict.get("code", "code")
# 'Row_code'
name_dict.get("work", "work") # Case sensitive
# 'work'
和 alias
只是将列 (df[col]
) 重命名为从 name_dict.get
.
返回的名称
我需要使用 pyspark
更改数据框df
相对于其他数据框 df_col
的列名
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|
+-----------+-----------+
如果 df 列匹配 col_current,df 列应替换为 col_updated。例如:如果 df.id 匹配 df.col_current,则 df.id 应替换为 Row_id。
预期输出
Row_id,Name,Row_code,Work_code
101,John,ASD,DEV
102,ben,klj,prod
注意:我希望这个过程是动态的。
只需收集 df_col
作为字典:
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()
并使用 select
和列表理解:
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)
其中 name_dict
是标准 Python 字典:
{'Work': 'Work_Code', 'code': 'Row_code', 'id': 'Row_id', 'name': 'Name'}
name_dict.get(c, c)
获取新名称、当前名称或当前名称(如果不匹配):
name_dict.get("code", "code")
# 'Row_code'
name_dict.get("work", "work") # Case sensitive
# 'work'
和 alias
只是将列 (df[col]
) 重命名为从 name_dict.get
.