开发者社区> 问答> 正文

如何通过索引重命名PySpark数据帧列?(处理重复的列名)

我需要动态更新Spark数据帧中的列。

基本上我需要遍历列列表,如果列已经存在于列表中,则将其重命名为该列及其索引。

我尝试过的代码是这样的:

def dup_cols(df):
for i, icol in enumerate(df.columns):

for x, xcol in enumerate(df.columns):
  if icol == xcol and i != x:
    df = df.withColumnsRenamed(xcol, xcol + '_' + str(x))

return df
但这会按名称重命名(此处为xcol),因此无法解决我的问题。

我可以更改此设置以通过索引重命名数据框中的列吗?我已经搜了好一会儿,一无所获。

我也无法转换为Pandas数据帧,因此我需要一个Spark / PySpark解决方案来仅通过其索引重命名特定列。

展开
收起
社区小助手 2018-12-21 11:58:43 2439 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    您可以使用pyspark.sql.DataFrame.toDF()重命名列:

    返回一个新类:具有新指定列名的DataFrame

    这是一个例子:

    data = [

    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9)

    ]

    df = spark.createDataFrame(data, ["a", "b", "a"])
    df.printSchema()

    root

    |-- a: long (nullable = true)

    |-- b: long (nullable = true)

    |-- a: long (nullable = true)

    根据索引逻辑创建新名称:

    new_names = []
    counter = {c: -1 for c in df.columns}
    for c in df.columns:

    new_c = c
    counter[c] += 1
    new_c += str(counter[c]) if counter[c] else ""
    new_names.append(new_c)

    print(new_names)

    ['a', 'b', 'a1']

    现在用于toDF()创建具有新列名称的新DataFrame:

    df = df.toDF(*new_names)
    df.printSchema()

    root

    |-- a: long (nullable = true)

    |-- b: long (nullable = true)

    |-- a1: long (nullable = true)

    2019-07-17 23:23:21
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载