2017-08-04 400 views
0

我在Pandas中创建了一些我试图转换为PySpark代码的代码。它使用urlparse Python库将通用URI解析为Python字典,将这些键转换为新列,然后将这些新列与原始数据连接起来。下面是一个简化的例子。在真实数据集中有38列,我关心保留所有这些列。将Python字典转换为PySpark中的稀疏RDD或DF

# create some sample data 
df_ex = pd.DataFrame([[102,'text1',u'/some/website/page.json?ovpevu&colc=1452802104103&si=569800363b029b74&rev=v4.1.2-wp&jsl=161&ln=en&pc=men&dp=www.mysite.com&qfq=news/this-is-an-article&of=2&uf=1&pd=0&irt=0&md=0&ct=1&tct=0&abt=0&lt=792&cdn=1&lnlc=gb&tl=c=141,m=433,i=476,xm=1243,xp=1254&pi=2&&rb=0&gen=100&callback=_ate.track.hsr&mk=some,key,words,about,the,article&'], 
      [781,'text2',u'/libtrc/hearst-network/loader.js'], 
      [9001,'text3',u'/image/view/-/36996720/highRes/2/-/maxh/150/maxw/150/mypic.jpg'], 
      [121,'text4',u'/website/page2.json?ovpevu&colc=1452802104103&si=569800363b029b74&rev=v4.1.2-wp&qqd=1&pd=0&irt=0&md=0&zzct=1&tct=0&abt=0&lt=792&cdn=0&lnlc=gb&tl=c=414,m=32,i=41,xm=1000,xp=111&callback=_ate.track.hsr&mk=some,other,key,words,about,the,article&'], 
      [781,'text5',u'/libtrc/hearst-network/loader.js']],columns=['num','text','uri']) 

# parse the URI to a dict using urlparse 
df_ex['uri_dict'] = df_ex['uri'].apply(lambda x: dict(urlparse.parse_qsl(urlparse.urlsplit(x).query))) 

# convert the parsed dict to a series 
df_ex_uridict_series = df_ex['uri_dict'].apply(pd.Series) 

# concatenate the parsed dict (now columns) back with original DF 
df_final = pd.concat([df_ex, df_ex_uridict_series], axis=1).drop('uri_dict', axis=1) 

的东西,看起来像这样(裁剪)得到的:

Result after parsing URI; Pandas DF (sparse matrix)

的结果是相当稀疏,但是这很好。对于应用程序,我实际上更喜欢它是一个稀疏矩阵(尽管我可以确信是否有一个很好的选择,密集的方法)。这就是我试图在PySpark中重新创建的结果。

到目前为止我所在的地方(在PySpark 2.1.0中)(使用相同的数据)。

# urlparse library 
import urlparse 

# create the sample data as RDD 
data = sc.parallelize([[102,'text1',u'/some/website/page.json?ovpevu&colc=1452802104103&si=569800363b029b74&rev=v4.1.2-wp&jsl=161&ln=en&pc=men&dp=www.mysite.com&qfq=news/this-is-an-article&of=2&uf=1&pd=0&irt=0&md=0&ct=1&tct=0&abt=0&lt=792&cdn=1&lnlc=gb&tl=c=141,m=433,i=476,xm=1243,xp=1254&pi=2&&rb=0&gen=100&callback=_ate.track.hsr&mk=some,key,words,about,the,article&'],[781,'text2',u'/libtrc/hearst-network/loader.js'],[9001,'text3',u'/image/view/-/36996720/highRes/2/-/maxh/150/maxw/150/mypic.jpg'],[121,'text4',u'/website/page2.json?ovpevu&colc=1452802104103&si=569800363b029b74&rev=v4.1.2-wp&qqd=1&pd=0&irt=0&md=0&zzct=1&tct=0&abt=0&lt=792&cdn=0&lnlc=gb&tl=c=414,m=32,i=41,xm=1000,xp=111&callback=_ate.track.hsr&mk=some,other,key,words,about,the,article&'],[781,'text5',u'/libtrc/hearst-network/loader.js']]) 

# simple map to parse the uri 
uri_parsed = data.map(list).map(lambda x: [x[0],x[1],urlparse.parse_qs(urlparse.urlsplit(x[2]).query)]) 

这让我非常接近,在RDD的每个“行”内嵌入了一个python字典。像这样:

In [187]: uri_parsed.take(3) 
Out[187]: 
[[102, 
    'text1', 
    {u'abt': [u'0'], 
    u'callback': [u'_ate.track.hsr'], 
    u'cdn': [u'1'], 
    u'colc': [u'1452802104103'], 
    u'ct': [u'1'], 
    u'dp': [u'www.mysite.com'], 
    u'gen': [u'100'], 
    u'irt': [u'0'], 
    u'jsl': [u'161'], 
    u'ln': [u'en'], 
    u'lnlc': [u'gb'], 
    u'lt': [u'792'], 
    u'md': [u'0'], 
    u'mk': [u'some,key,words,about,the,article'], 
    u'of': [u'2'], 
    u'pc': [u'men'], 
    u'pd': [u'0'], 
    u'pi': [u'2'], 
    u'qfq': [u'news/this-is-an-article'], 
    u'rb': [u'0'], 
    u'rev': [u'v4.1.2-wp'], 
    u'si': [u'569800363b029b74'], 
    u'tct': [u'0'], 
    u'tl': [u'c=141,m=433,i=476,xm=1243,xp=1254'], 
    u'uf': [u'1']}], 
[781, 'text2', {}], 
[9001, 'text3', {}]] 

这些值包含列表,但没关系。他们可以留在列表中。

我现在想要做的是从字典中解析出键/值对(如Pandas中),从键创建新列,然后将值(或值列表)案件)在RDD中。

有些事情我已经试过:

  • 走向全面的PySpark DF:写了一个UDF,并使用with_column建立在DF的新列应用。这是有效的,但它将整个词典作为一个单独的字符串(没有键和值在引号中)。我没有试图推动这一点,并添加引号(认为有更好的方法)。
  • 拆分原始DF:首先使用monotonically_increasing_id()为每个DF行分配一个唯一ID,拆分两列(新ID和URI),将拆分转换为RDD,然后解析。这会让我再回来(使用ID),但它并没有帮助创建我想要的“稀疏矩阵”。

我还发现这些技术(使用Spark v2.1.0和Hive数据存储)可能不是用于表示此类数据的正确底层技术。也许一个无模式的数据存储会更好。但是,我现在限制使用Spark和Hive作为数据存储。

任何帮助将不胜感激!

回答

1

我最近在查看类似的问题,解析包含由'='分隔的键值对的字符串,其中可能的键事先并不知道。

我不确定这是否是最有效的解决方案,但我提出了一个解决方案,该解决方案通过rdd运行几次来发现和处理任意标签。

首先,解析出该标签的行中的URL和num文本对:

def urlparsefn(url): 
    return urlparse.parse_qs(urlparse.urlsplit(url).query) 

# parse the uri to a dictionary 
uri_parsed = data.map(lambda x: (x[0],x[1],urlparsefn(x[2]))) 

然后你就可以通过提取每个URI字典的唯一密钥,然后聚集在一起使用提取所有不同的标签Python set,它可以让你轻松删除重复项。

# We need to discover all the unique keys before we will know which columns our data frame will have 
combOp = (lambda x, y: x.union(y)) 
possible_keys_set = uri_parsed.map(lambda x: set(x[2].keys())).aggregate(set(), combOp, combOp) 
possible_keys = sorted(list(possible_keys_set)) # sets have no order, this will give us alphabetical order in the final dataframe 

现在,我们拥有所有的唯一可能的密钥,我们可以提取不同NUM和文本标签的行,并确保每个字典中有所有的标签,使用一些占位符文本的元素不存在于特定的uri字典中。然后,您可以使用Python中的关键字参数构建一行rdd。

def attrmap(urirow, possible_keys): 
    # Extract the 3 parts of the uri tuple 
    num = urirow[0] 
    text = urirow[1] 
    uridict = urirow[2] 

    # Assign the known fields identifying the row 
    uridict['num'] = num 
    uridict['text'] = text 

    # Run through the possible keys, add a placeholder for any keys not present in the row 
    for key in possible_keys: 
     if key not in uridict: 
      uridict[key] = 'N/A' # Some place holder for values in the list of possible keys, but not in the current uri dictionary 
     else: 
      uridict[key] = uridict[key][0] # All the lists only have 1 item, so just extract the item 

    return uridict 

# Create an rdd of Row type, using the dictionary as kwargs 
uri_allkeys = uri_parsed.map(lambda x: Row(**attrmap(x, possible_keys))) 

然后最后一件事就是根据num,text和所有提取的可能列构建新数据框架。

# Create an item in the schema for the known fields, and each possible key 
df_schema = StructType() 
for possible_key in ['num','text']+possible_keys: 
    df_schema.add(possible_key, StringType(), True) 

# Use the new schema and rdd of rows to create the dataframe 
uri_parsed_df = spark.createDataFrame(uri_allkeys, df_schema) 

这应该给任意列的数据帧。希望这可以帮助!