Python 类型错误:can';t将序列乘以类型为'的非整数;numpy.float64';-将列乘以值
通过将现有列乘以一个值,我在数据框中创建新列时遇到问题-我查看了类似的问题,但无法理解如何修复下面的代码:Python 类型错误:can';t将序列乘以类型为'的非整数;numpy.float64';-将列乘以值,python,python-3.x,Python,Python 3.x,通过将现有列乘以一个值,我在数据框中创建新列时遇到问题-我查看了类似的问题,但无法理解如何修复下面的代码: list = [] i = 1 for col in df.columns[1:19]: #calculations x = df[[df.columns[i], df.columns[i+1], df.columns[i+2]]].values Q = np.cov(x.T) eval, evec = np.linalg.eig(Q) w
list = []
i = 1
for col in df.columns[1:19]:
#calculations
x = df[[df.columns[i], df.columns[i+1], df.columns[i+2]]].values
Q = np.cov(x.T)
eval, evec = np.linalg.eig(Q)
w = np.array([2*(evec[0,2]/evec[1,2]),2*(evec[1,2]/evec[1,2]),2*(evec[2,2]/evec[1,2])])
#create new columns in dataframe with applied weights
df['w1_PCA'] = df.columns[i] * w[0]
df['b_PCA'] = df.columns[i+1] * w[1]
df['w2_PCA'] = df.columns[i+2] * w[2]
i = i + 1
print(x)
接收错误如下:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-d7d86010b8f8> in <module>
19
20 #create new columns in dataframe for back-applied PCA weights
---> 21 df['w1_PCA'] = df.columns[i] * w[0]
22 df['b_PCA'] = df.columns[i+1] * w[1]
23 df['w2_PCA'] = df.columns[i+2] * w[2]
TypeError: can't multiply sequence by non-int of type 'numpy.float64'
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
19
20#在dataframe中为反向应用的PCA权重创建新列
--->21 df['w1_PCA']=df.列[i]*w[0]
22 df['b_PCA']=df.列[i+1]*w[1]
23 df['w2_PCA']=df.列[i+2]*w[2]
TypeError:无法将序列与类型为'numpy.float64'的非整数相乘
有人能告诉我这个问题出在哪里吗
非常感谢您的帮助 抛出错误是因为数据帧df的列号i是字符串(在我的代码中)或整数。首先需要使用
float()
将int转换为float。
我为您的问题创建了一个简短的示例,并且可以按照我的理解消除错误,同时添加另外三列并插入一些值。我希望您可以将此解决方案应用于数据帧或数据集。下面你可以找到两个例子,具体取决于你想做什么
解决方案1:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c': [2,3,4], 'd': [2,3,4], 'e': [2,3,4], 'f': [2,3,4], 'g': [2,3,4]})
list = []
i = 1
for col in df.columns[1:5]:
#calculations
x = df[[df.columns[i], df.columns[i+1], df.columns[i+2]]].values
Q = np.cov(x.T)
eval, evec = np.linalg.eig(Q)
w = np.array([2*(evec[0,2]/evec[1,2]),2*(evec[1,2]/evec[1,2]),2*(evec[2,2]/evec[1,2])])
#create new columns in dataframe with applied weights
df['w1_PCA'] = float(df['a'][0]) * w[0]
df['b_PCA'] = float(df['b'][0]) * w[1]
df['w2_PCA'] = df['c'][0] * w[2]
i = i + 1
在这种情况下,产生的df
为:
a b c d e f g w1_PCA b_PCA w2_PCA
0 1 2 2 2 2 2 2 -0.0 4.0 -4.0
1 2 3 3 3 3 3 3 -0.0 4.0 -4.0
2 3 4 4 4 4 4 4 -0.0 4.0 -4.0
或者,您可以在列df['a']
上应用函数,并将结果存储在新列中。您必须将代码的第21到23行更改为下面的三行。
下面是函数到整个列的映射:
解决方案2
df['w1_PCA'] = df['a'].apply(lambda x: float(x) * w[0])
df['b_PCA'] = df['b'].apply(lambda x: float(x) * w[1])
df['w2_PCA'] = df['c'].apply(lambda x: float(x) * w[2])
结果:
a b c d e f g w1_PCA b_PCA w2_PCA
0 1 2 2 2 2 2 2 -0.0 4.0 -4.0
1 2 3 3 3 3 3 3 -0.0 6.0 -6.0
2 3 4 4 4 4 4 4 -0.0 8.0 -8.0