list - 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',
........]
我正在尝试匹配vocablist
to 。termIndices
termWeights
到目前为止,我有以下内容:
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, ......)
任何帮助将不胜感激。
解决方案
我建议您将它们分散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()
我希望这有帮助。
推荐阅读
- python-3.x - 使用python将公式添加到excel电子表格
- javascript - 如何在animejs中用逗号动画计数数字?
- discord.py - 机器人不和谐审核的问题
- json - Oracle Rest 数据服务以 JSON 形式返回集合
- java - Android Studio:在ScrollView中调用多个Canvas依次显示1个绘图(canvas)
- python - 未定义全局变量 - Python 和 PyGame
- swift - SwiftUI 2:在新窗口中打开视图的方式
- r - R子集内部级别嵌套数据框
- angular - 角按钮出现两次为什么?
- ios - Swift UI - 图片库上的按钮返回