首页 > 解决方案 > pandas中pyspark数据框的匹配索引

问题描述

我有以下 pyspark 数据框(testDF=ldamodel.describeTopics().select("termIndices").toPandas()

topic|    termIndices|         termWeights|
+-----+---------------+--------------------+
|    0|    [6, 118, 5]|[0.01205522104545...|
|    1|   [0, 55, 100]|[0.00125521761966...|

我有以下单词列表

['one',
 'peopl',
 'govern',
 'think',
 'econom',
 'rate',
 'tax',
 'polici',
 'year',
 'like',
........]

我正在尝试匹配vocablistto 。termIndicestermWeights

到目前为止,我有以下内容:

for i in testDF.items():
    for j in i[1]:
        for m in j:
            t=vocablist[m],m
            print(t)

结果是:

('tax', 6)
('insur', 118)
('rate', 5)
('peopl', 1)
('health', 84)
('incom', 38)
('think', 3)
('one', 0)
('social', 162)
.......

但我想要类似的东西

('tax', 6, 0.012055221045453202)
('insur', 118, 0.001255217619666775)
('rate', 5, 0.0032220995010401187)

('peopl', 1,0.008342115226031033)
('health', 84,0.0008332053105123403)
('incom', 38, ......)

任何帮助将不胜感激。

标签: listpandaspyspark

解决方案


我建议您将它们分散lists在列中termIndices并向termWeights下传播。完成此操作后,您实际上map可以为其术语名称编制索引,同时使术语权重与每个术语索引保持一致。下面是一个插图:

df = pd.DataFrame(data={'topic': [0, 1],
                        'termIndices': [[6, 118, 5],
                                        [0, 55, 100]],
                        'termWeights': [[0.012055221045453202, 0.012055221045453202, 0.012055221045453202],
                                        [0.00125521761966, 0.00125521761966, 0.00125521761966]]})

dff = df.apply(lambda s: s.apply(pd.Series).stack().reset_index(drop=True, level=1))

vocablist = ['one', 'peopl', 'govern', 'think', 'econom', 'rate', 'tax', 'polici', 'year', 'like'] * 50

dff['termNames'] = dff.termIndices.map(vocablist.__getitem__)

dff[['termNames', 'termIndices', 'termWeights']].values.tolist()

我希望这有帮助。


推荐阅读