最佳答案
您可以使用 np.argsort
或 np.argpartition
获取排序索引。按照指示的问题的程序
# With argsort
most_important = [np.argsort(np.abs(model.components_[i]))[::-1][:3] for i in range(n_pcs)]
# With argpartition
most_important = [np.argpartition(np.abs(model.components_[i]), -3)[-3:] for i in range(n_pcs)]
most_important
>>> [array([4, 1, 0]), array([2, 3, 4])]
然后获取最重要的组件作为列
initial_feature_names = ['a','b','c','d','e']
# Notices the [::-1] is used to order the component names
most_important_names = [[initial_feature_names[i] for i in most_important[i][::-1]] for i in range(n_pcs)]
dic = {'PC{}'.format(i): most_important_names[i] for i in range(n_pcs)}
pd.DataFrame.from_dict(dic).T
>>>
0 1 2
PC0 e b a
PC1 c d e
关于python - 如何使用 Pandas 找到每个主成分的前三个特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64299847/