如何替换pyspark Dataframe 的列名中的字符串?

uqzxnwby  于 2023-05-16  发布在  Spark
关注(0)|答案(2)|浏览(216)

我有一个pyspark Dataframe ,每个列都附加了表名,即:Table.col1、Table.col2...
我想在我的数据框架中的每一列中将'Table.'替换为''(nothing)。
我该怎么做?我所发现的一切都是针对列中的值而不是列名本身进行的。

aelbi1ox

aelbi1ox1#

一种选择是将toDFreplace一起使用:
DataFrame.toDF(*cols)
返回一个新的DataFrame,它带有新指定的列名

out = df.toDF(*[c.replace("Table.", "") for c in df.columns])

输出:

out.show()
+----+----+
|col1|col2|
+----+----+
| foo|   1|
| bar|   2|
+----+----+
  • 使用的输入:*
+----------+----------+
|Table.col1|Table.col2|
+----------+----------+
|       foo|         1|
|       bar|         2|
+----------+----------+
xwbd5t1u

xwbd5t1u2#

PySpark中执行:

from pyspark.sql.functions import col
new_columns = [col(column_name).alias(column_name.replace('Table.', '')) for column_name in df.columns]
df_new = df.select(new_columns)

另外,如果有人想在Pandas中做同样的事情:

df.columns = df.columns.str.replace('Table.', '')

相关问题