Pyspark - Использование функции карты для заполнения словаря - PullRequest
1 голос
/ 01 ноября 2019

Мой первый пост: я пытаюсь создать словарь ингредиентов со значением SparseVector, где их расположение соответствует рецептам, использующим этот ингредиент.

У меня есть датафрейм, преобразованный в rdd ... rddData = data.rdd.map(list).zipWithIndex()

Одна строка rdd выглядит следующим образом

([426.0,
   [u'Sandwich',
    u'Bean',
    u'Fruit',
    u'Tomato',
    u'turkey',
    u'Vegetable',
    u'Kid-Friendly',
    u'Apple',
    u'Lentil',
    u'Lettuce',
    u'Cookie'],
   u'2006-09-01T04:00:00.000Z',
   None,
   [u'1. Place the stock, lentils, celery, carrot, thyme, and salt in a medium saucepan and bring to a boil. Reduce heat to low and simmer until the lentils are tender, about 30 minutes, depending on the lentils. (If they begin to dry out, add water as needed.) Remove and discard the thyme. Drain and transfer the mixture to a bowl; let cool.',
    u'2. Fold in the tomato, apple, lemon juice, and olive oil. Season with the pepper.',
    u'3. To assemble a wrap, place 1 lavash sheet on a clean work surface. Spread some of the lentil mixture on the end nearest you, leaving a 1-inch border. Top with several slices of turkey, then some of the lettuce. Roll up the lavash, slice crosswise, and serve. If using tortillas, spread the lentils in the center, top with the turkey and lettuce, and fold up the bottom, left side, and right side before rolling away from you.'],
   7.0,
   [u'kosher salt', u'extravirgin olive oil'],
   30.0,
   2.5,
   559.0,
   u'Lentil, Apple, and Turkey Wrap '],
  0)

Здесь кошерная соль и extravirgin оливковоемасло - это ингредиенты, которые являются единственной частью данных, которыми я сейчас занимаюсь. Я создал словарь всех уникальных ингредиентов, выполнив

ingrList = data.rdd.flatMap(lambda x : x[6]).distinct().collect()
for item in ingrList:
    ingr[item] =[[],[]]

Первый массив будет индексом рецепта, а второй - значением, равным 1, я сделал функцию карты, которая должна быладобавить значения к каждому из них, но при использовании

def mapIngr(recipe):
    for item in recipe[0][6]:  # this is the list of ingredients
        ingr[item][0].append(recipe[1])  # recipe[1] is the index of the recipe 
        ingr[item][1].append(1)
    return recipe
rddData.map(mapIngr)

ничего не происходит. Я протестировал функцию одной строкой, и она работает, но при отображении всего rdd словарь не заполняется.

Цель состоит в том, чтобы взять два массива значения и создать SparseVector после того, как у меня есть все индексы, в которых есть рецепты каждого ингредиента. Не уверен, что есть лучший подход.

...