[英]Pyspark dataframe replace functions: How to work with special characters in column names?
[英]Conditional replace of special characters in pyspark dataframe
我在pyspark中有數據框df。 它具有eng hours,eng_hours,test apt,test.rest等列...
我想用下划線(_)替換列名中的空格和點。
如果在替換列之后,如果有重復項,則返回我們替換字符並連接它的列名稱。
例如:在上面的數據框中,我們有兩列eng hours和eng_hours。 現在,在第一列中用下划線替換空格后,我們將獲得eng_hours,它將與第二列eng_hours重復。 當出現這種情況時,請以整點返回第一列。
我們如何在pyspark中實現這一目標。
做了一些小的更改以包括列名重復的部分,請嘗試此操作,
>>> from pyspark.sql.types import *
>>>import re
>>> l=[('val1','val2','val3'),('val4','val5','val6')]
>>> l_schema = StructType([StructField("eng hours",StringType(),True),StructField("eng_hours",StringType(),True),StructField("test.apt",StringType(),True)])
>>> rdd = sc.parallelize(l)
>>> df = sqlContext.createDataFrame(rdd,l_schema)
>>> reps=('.','_'),(' ','_')
>>> df.printSchema()
root
|-- eng hours: string (nullable = true)
|-- eng_hours: string (nullable = true)
|-- test.apt: string (nullable = true)
>>> colnames = df.schema.names
>>> def colrename(x):
... newcol = reduce(lambda a,kv : a.replace(*kv),reps,x)
... return re.sub('[. ]','',x) if newcol in colnames else newcol
>>> for i in colnames:
... df = df.withColumnRenamed(i,colrename(i))
>>> df.printSchema()
root
|-- enghours: string (nullable = true)
|-- eng_hours: string (nullable = true)
|-- test_apt: string (nullable = true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.