【问题标题】:PySpark dynamic Column Renaming not workingPySpark 动态列重命名不起作用
【发布时间】:2022-01-04 17:31:59
【问题描述】:

我正在尝试使用以下方法动态重命名 Pyspark 中的列。但是只有一列被重命名而不是全部

target_schema : ['customer_Number', ' product_Number', ' Payment_Term', ' DateTime', ' Company_ID', ' Company_Number', ' Col1', ' Col2']
source_schema : ['customerID', ' productID', ' Paymentterm', ' datetime', ' xyzID']

display(df_xyz)

output of the dataframe

df_rename_schema = df_xyz.select([col(c).alias(source_target_mapping.get(c, c)) for c in df_xyz.columns])

df_modified_source_schema = df_rename_schema.columns
print(df_modified_source_schema)

Output : ['productID', 'customer_Number', 'Paymentterm', 'datetime', 'xyzID']

Expected Output : ['product_Number', ' customer_Number', ' Payment_Term', 'DateTime','Company_ID']

请帮助这里出了什么问题以及如何实现解决方案

【问题讨论】:

  • 你能分享source_target_mapping 映射吗,我看到列名包含空格,也许字典不包含空格,迫使source_target_mapping.get(c, c) 返回默认值,即源列名。

标签: azure pyspark dynamic


【解决方案1】:

假设您的source_target_mapping 不考虑df_xyz 列名中的空格。您可以在查找操作之前去除列名中的空格。

df_rename_schema = df_xyz.select([F.col(c).alias(source_target_mapping.get(c.strip(), c)) for c in df_xyz.columns])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2022-10-05
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多