首页 > 解决方案 > 如何对 numpy 元组进行排序而不会出现关于只有长度为 1 的数组的错误可以转换为 python 标量

问题描述

我正在使用 numpy 生成特征向量和特征值。当形成它们的元组并尝试对这些对进行排序时会出现问题。我收到错误消息:TypeError:只有长度为 1 的数组可以转换为 python 标量。

这是代码:

import numpy as np
import pandas as pd


df=\
pd.read_csv(r'C:\Users\james\Desktop\Documents\Downloads\bpAFTPosWords.csv'
#df.head()

#Drop columns whose sum is less than 30
df.sum(axis = 0, skipna = True)
df_to_save = df.loc[:, (df.sum(axis=0, skipna=True) >= 30)]
#df_to_save.head()

#Standardize the data
from sklearn.preprocessing import StandardScaler
X_std = StandardScaler().fit_transform(df_to_save)

#Compute correlations
cor_mat1 = np.corrcoef(X_std.T)
#Produce PCA eigenvector and eigenvalues
eig_vals, eig_vecs = np.linalg.eig(cor_mat1)

#print('Eigenvectors \n%s' %eig_vecs)
#print('\nEigenvalues \n%s' %eig_vals)

# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = np.array(list(zip(eig_vals,eig_vecs)))
eig_pairs = eig_pairs[
        eig_pairs[:,0].argsort()[::-1]]

# Visually confirm that the list is correctly sorted by decreasing
print('Eigenvalues in descending order:')
for i in eig_pairs:
print(i[0])

#Here is the context for the error:
TypeError Traceback (most recent call last)
<ipython-input-7-2342d13b7710> in <module>
21
22 # Make a list of (eigenvalue, eigenvector) tuples
---> 23 eig_pairs = np.array(list(zip(eig_vals,eig_vecs)))
24
25 eig_pairs = eig_pairs[
TypeError: only length-1 arrays can be converted to Python scalars

如果我的数据有助于您解决问题,这里是 .csv 文件:

https://docs.google.com/spreadsheets/d/1GRPbfHHB1mbO5Eo26B6crTl7FN1cNnLoU-oRQCEu7v8/edit?usp=sharing

我的第二个问题是如何将每个特征向量上的每一行的负载输出到文件中。尚未能够从谷歌搜索和文档中弄清楚这一点。

谢谢你的帮助!

标签: pythonpandasnumpysklearn-pandas

解决方案


我无法重现您的错误,但这是基于 numpy 排序的解决方案。

import numpy as np

X_std = np.random.random((8,8))

cor_mat1 = np.corrcoef(X_std.T)
eig_vals, eig_vecs = np.linalg.eig(cor_mat1)

print('Eigenvectors \n%s' %eig_vecs)
print('\nEigenvalues \n%s' %eig_vals)

# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = np.array(list(zip(eig_vals,eig_vecs)))

eig_pairs = eig_pairs[
        eig_pairs[:,0].argsort()[::-1]
                 ]

# Visually confirm that the list is correctly sorted by decreasing 
print('Eigenvalues in descending order:')
for i in eig_pairs:
    print(i[0])

在这里你可以阅读关于 zip 功能和这里关于 argsort

希望有帮助。


推荐阅读