Как я могу использовать Apache Spark и lxml для анализа, фильтрации и агрегирования данных? - PullRequest
0 голосов
/ 05 ноября 2019

Я создал общий XMLparser из lxml , используя etree.fromstring(x). Теперь мне нужно проанализировать XML, как показано ниже:

 <row AcceptedAnswerId="88156" AnswerCount="6" Body="&lt;p&gt;I\'ve just played a game with my kids that basically boils down to: whoever rolls every number at least once on a 6-sided dice wins.&lt;/p&gt;&#10;&#10;&lt;p&gt;I won, eventually, and the others finished 1-2 turns later. Now I\'m wondering: what is the expectation of the length of the game?&lt;/p&gt;&#10;&#10;&lt;p&gt;I know that the expectation of the number of rolls till you hit a specific number is &#10;$\\sum_{n=1}^\\infty n\\frac{1}{6}(\\frac{5}{6})^{n-1}=6$.&lt;/p&gt;&#10;&#10;&lt;p&gt;However, I have two questions:&lt;/p&gt;&#10;&#10;&lt;ol&gt;&#10;&lt;li&gt;How many times to you have to roll a six-sided dice until you get every number at least once? &lt;/li&gt;&#10;&lt;li&gt;Among four independent trials (i.e. with four players), what is the expectation of the &lt;em&gt;maximum&lt;/em&gt; number of rolls needed? [note: it\'s maximum, not minimum, because at their age, it\'s more about finishing than about getting there first for my kids]&lt;/li&gt;&#10;&lt;/ol&gt;&#10;&#10;&lt;p&gt;I can simulate the result, but I wonder how I would go about calculating it analytically.&lt;/p&gt;&#10;&#10;&lt;hr&gt;&#10;&#10;&lt;p&gt;Here\'s a Monte Carlo simulation in Matlab&lt;/p&gt;&#10;&#10;&lt;pre&gt;&lt;code&gt;mx=zeros(1000000,1);&#10;for i=1:1000000,&#10;   %# assume it\'s never going to take us &amp;gt;100 rolls&#10;   r=randi(6,100,1);&#10;   %# since R2013a, unique returns the first occurrence&#10;   %# for earlier versions, take the minimum of x&#10;   %# and subtract it from the total array length&#10;   [~,x]=unique(r); &#10;   mx(i,1)=max(x);&#10;end&#10;&#10;%# make sure we haven\'t violated an assumption&#10;assert(~any(mx==100))&#10;&#10;%# find the expected value for the coupon collector problem&#10;expectationForOneRun = mean(mx)&#10;&#10;%# find the expected number of rolls as a maximum of four independent players&#10;maxExpectationForFourRuns = mean( max( reshape( mx, 4, []), [], 1) )&#10;&#10;expectationForOneRun =&#10;   14.7014 (SEM 0.006)&#10;&#10;maxExpectationForFourRuns =&#10;   21.4815 (SEM 0.01)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;" CommentCount="5" CreationDate="2013-01-24T02:04:12.570" FavoriteCount="9" Id="48396" LastActivityDate="2014-02-27T16:38:07.013" LastEditDate="2013-01-26T13:53:53.183" LastEditorUserId="198" OwnerUserId="198" PostTypeId="1" Score="23" Tags="&lt;probability&gt;&lt;dice&gt;" Title="How often do you have to roll a 6-sided dice to obtain every number at least once?" ViewCount="5585" />',
 '  <row AnswerCount="1" Body="&lt;p&gt;Suppose there are $6$ people in a population. During $2$ weeks $3$ people get the flu. Cases of the flu last $2$ days. Also people will get the flu only once during this period. What is the incidence density of the flu?&lt;/p&gt;&#10;&#10;&lt;p&gt;Would it be $\\frac{3}{84 \\text{person days}}$ since each person is observed for $14$ days?&lt;/p&gt;&#10;" CommentCount="4" CreationDate="2013-01-24T02:23:13.497" Id="48397" LastActivityDate="2013-04-24T16:58:18.773" OwnerUserId="20010" PostTypeId="1" Score="1" Tags="&lt;epidemiology&gt;" Title="Incidence density" ViewCount="288" />',

Предположим, что моя цель - извлечь значения CommentCount и агрегировать их. Поскольку я делаю это через PySpark, это, конечно, только очень небольшая выборка данных.

Я пытался использовать мой анализатор совместно с .filter(), reduceByKey, но убежищене было большого успеха. Предположительно мой парсер lxml, упомянутый выше, возвращает словарь, хотя я не смог подтвердить, что это так.

Может ли кто-нибудь объяснить лучший способ агрегирования значений CommentCount в приведенном выше XML-файле?

Примечание: блоки данных не могут быть установлены в моей системе, любое решение не должно требовать этого.

...