2017-09-26 127 views
0

我是pyspark數據框的新手,並且曾經使用過RDD。我有這樣一個數據幀:修改列pyspark數據幀的所有值

date  path 
2017-01-01 /A/B/C/D 
2017-01-01 /X 
2017-01-01 /X/Y 

而且要轉換爲以下幾點:

date  path 
2017-01-01 /A/B 
2017-01-01 /X 
2017-01-01 /X/Y 

基本上第三/包括之後擺脫一切。因此,與前RDD以前我有以下幾點:

from urllib import quote_plus 

path_levels = df['path'].split('/') 
filtered_path_levels = [] 
for _level in range(min(df_size, 3)): 
    # Take only the top 2 levels of path 
    filtered_path_levels.append(quote_plus(path_levels[_level])) 

df['path'] = '/'.join(map(str, filtered_path_levels)) 

事情pyspark比較複雜,我會說。以下是我迄今爲止得到:

path_levels = split(results_df['path'], '/') 
filtered_path_levels = [] 
for _level in range(size(df_size, 3)): 
    # Take only the top 2 levels of path 
    filtered_path_levels.append(quote_plus(path_levels[_level])) 

df['path'] = '/'.join(map(str, filtered_path_levels)) 

這是給我下面的錯誤:

ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions. 

任何改編職系這幫助將非常感激。讓我知道這是否需要更多的信息/解釋。

回答

0

我用下面的代碼解決了我的問題:

from pyspark.sql.functions import split, col, lit, concat 

split_col = split(df['path'], '/') 
df = df.withColumn('l1_path', split_col.getItem(1)) 
df = df.withColumn('l2_path', split_col.getItem(2)) 
df = df.withColumn('path', concat(col('l1_path'), lit('/'), col('l2_path'))) 
df = df.drop('l1_path', 'l2_path') 
0

使用udf

from pyspark.sql.functions import * 

@udf 
def quote_string_(path, size): 
    if path: 
     return "/".join(quote_plus(x) for x in path.split("/")[:size]) 

df.withColumn("foo", quote_string_("path", lit(2))) 
+0

謝謝,但與UDF的問題是,它原來是很慢特意用非常大的交易時數據(在我的情況下是TB),所以我決定堅持其他的pyspark功能。 – ahajib