如何按索引重命名PySpark数据框列? (处理重复的列名)

时间:2018-12-13 17:55:48

标签: python apache-spark dataframe 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解决方案来仅通过其索引重命名特定列。

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用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)

答案 1 :(得分:-1)

假设dt是当前数据帧

new_columns = []

for i in range(1, len(dt.columns)):

   new_columns.append("new_column_name)

for c, n in zip(dt.columns[1:], new_columns):

    dt = dt.withColumnRenamed(c, n)