vde*_*dep 9 scala apache-spark apache-spark-sql spark-dataframe
我有火花数据帧,其中一些列名称中有空格,必须用下划线替换.
我知道可以使用withColumnRenamed()sparkSQL重命名单个列,但要重命名'n'个列,这个函数必须链接'n'次(据我所知).
要自动执行此操作,我尝试过:
val old_names = df.columns()        // contains array of old column names
val new_names = old_names.map { x => 
   if(x.contains(" ") == true) 
      x.replaceAll("\\s","_") 
   else x 
}                    // array of new column names with removed whitespace.
Run Code Online (Sandbox Code Playgroud)
现在,如何用.替换df的标头 new_names
Igo*_*man 15
  var newDf = df
  for(col <- df.columns){
    newDf = newDf.withColumnRenamed(col,col.replaceAll("\\s", "_"))
  }
Run Code Online (Sandbox Code Playgroud)
你可以用某种方法封装它,这样就不会有太多的污染.
Hug*_*yes 11
在Python中,这可以通过以下代码完成:
# Importing sql types
from pyspark.sql.types import StringType, StructType, StructField
from pyspark.sql.functions import col
# Building a simple dataframe:
schema = StructType([
             StructField("id name", StringType(), True),
             StructField("cities venezuela", StringType(), True)
         ])
column1 = ['A', 'A', 'B', 'B', 'C', 'B']
column2 = ['Maracaibo', 'Valencia', 'Caracas', 'Barcelona', 'Barquisimeto', 'Merida']
# Dataframe:
df = sqlContext.createDataFrame(list(zip(column1, column2)), schema=schema)
df.show()
exprs = [col(column).alias(column.replace(' ', '_')) for column in df.columns]
df.select(*exprs).show()
Run Code Online (Sandbox Code Playgroud)
        kan*_*elc 10
作为最佳实践,您应该更喜欢表达式和不变性。您应该使用val和不 var尽可能地。
因此,foldLeft在这种情况下,最好使用运算符:
val newDf = df.columns
              .foldLeft(df)((curr, n) => curr.withColumnRenamed(n, n.replaceAll("\\s", "_")))
Run Code Online (Sandbox Code Playgroud)
        Vic*_*nde 10
你可以在 python 中做同样的事情:
raw_data1 = raw_data
for col in raw_data.columns:
  raw_data1 = raw_data1.withColumnRenamed(col,col.replace(" ", "_"))
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           13515 次  |  
        
|   最近记录:  |