我有一个pyspark Dataframe ,每个列都附加了表名,即:Table.col1、Table.col2...我想在我的数据框架中的每一列中将'Table.'替换为''(nothing)。我该怎么做?我所发现的一切都是针对列中的值而不是列名本身进行的。
aelbi1ox1#
一种选择是将toDF与replace一起使用:DataFrame.toDF(*cols)返回一个新的DataFrame,它带有新指定的列名
toDF
replace
DataFrame.toDF(*cols)
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| +----------+----------+
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.', '')
2条答案
按热度按时间aelbi1ox1#
一种选择是将
toDF
与replace
一起使用:DataFrame.toDF(*cols)
返回一个新的DataFrame,它带有新指定的列名
输出:
xwbd5t1u2#
在PySpark中执行:
另外,如果有人想在Pandas中做同样的事情: