2017-10-14 137 views
-1

Pyspark n00b ...我如何用自己的子字符串替換列?我試圖從字符串的開頭和結尾刪除選定數量的字符。Pyspark alter column with substring

from pyspark.sql.functions import substring 
import pandas as pd 
pdf = pd.DataFrame({'COLUMN_NAME':['_string_','_another string_']}) 
# this is what i'm looking for... 
pdf['COLUMN_NAME_fix']=pdf['COLUMN_NAME'].str[1:-1] 

df = sqlContext.createDataFrame(pdf) 
# following not working... COLUMN_NAME_fix is blank 
df.withColumn('COLUMN_NAME_fix', substring('COLUMN_NAME', 1, -1)).show() 

這是非常接近,但略有不同Spark Dataframe column with last character of other column。再有就是這個 LEFT and RIGHT function in PySpark SQL

回答

2

pyspark.sql.functions.substring(STR,POS,LEN)

子串開始於POS和是長度LEN的時str是字符串類型或返回的切片字節數組開始於在字節POS和是長度LEN的時str是二元型

在代碼中,

df.withColumn('COLUMN_NAME_fix', substring('COLUMN_NAME', 1, -1)) 
1 is pos and -1 becomes len, length can't be -1 and so it returns null 

嘗試此,(具有固定的語法)

from pyspark.sql.types import StringType 
from pyspark.sql.functions import udf 

udf1 = udf(lambda x:x[1:-1],StringType()) 
df.withColumn('COLUMN_NAME_fix',udf1('COLUMN_NAME')).show() 
+0

偉大的作品謝謝! – citynorman

-1

嘗試:

df.withColumn('COLUMN_NAME_fix', df['COLUMN_NAME'].substr(1, 10)).show() 

其中1 =字符串中開始位置和 10 =字符數從開始位置包括(含)

+1

如果長度是動態的呢? – citynorman

+0

使用:_df ['COLUMN_NAME']。substr(startPos,strLength)_其中_startPos_是變量的起始位置,_strLength_是要包含的字符數的可變長度 – gps

+1

是的,如果'strLength'在樣本之間變化,我上面的例子 – citynorman

相關問題