字符串浮点错误在我的python项目中

时间:2018-07-12 13:01:27

标签: python database string spyder

# Python code to demonstrate SQL to fetch data.

# importing the module
import sqlite3
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from scipy.stats import chisquare

# connect withe the myTable database
connection = sqlite3.connect(r"C:\Users\Aidan\Desktop\CEP_DB.db")

# cursor object
crsr = connection.cursor()


dog= crsr.execute("Select s, ei, ki FROM cep_db_lite1_vc WHERE s IN ('d')")
ans= crsr.fetchall() 


filtered_data = ans[~np.isnan(ans["ki"])] 


dogData = np.array(filtered_data)
dogData.astype(float)
FdogData= dogData[:, [1,2]]
x, y = FdogData[:,0], FdogData[:,1]

# Reshaping
x, y = x.reshape(-1,1), y.reshape(-1, 1)

# Linear Regression Object 
lin_regression = LinearRegression()

# Fitting linear model to the data
lin_regression.fit(x,y)

# Get slope of fitted line
m = lin_regression.coef_

# Get y-Intercept of the Line
b = lin_regression.intercept_

# Get Predictions for original x values
# you can also get predictions for new data
predictions = lin_regression.predict(x)
chi= chisquare(predictions, y)

# following slope intercept form 
print ("formula: y = {0}x + {1}".format(m, b)) 
print(chi)

# Plot the Original Model (Black) and Predictions (Blue)
plt.scatter(x, y,  color='black')
plt.plot(x, predictions, color='blue',linewidth=3)
plt.show()
  

错误:runfile('C:/Users/Aidan/.spyder-py3/temp.py',   wdir ='C:/Users/Aidan/.spyder-py3')追溯(最近一次通话结束):

     

文件“”,第1行,在       运行文件('C:/Users/Aidan/.spyder-py3/temp.py',wdir ='C:/Users/Aidan/.spyder-py3')

     

文件   “ C:\ Users \ Aidan \ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py”,   运行文件中的第705行       execfile(文件名,命名空间)

     

文件   “ C:\ Users \ Aidan \ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py”,   第102行,在execfile中       exec(compile(f.read(),文件名,'exec'),命名空间)

     

文件“ C:/Users/Aidan/.spyder-py3/temp.py”,第22行,在       filtered_data = ans [〜np.isnan(ans [“ ki”])]

     

TypeError:列表索引必须是整数或切片,而不是str

我相信我在此部分收到错误:

dog= crsr.execute("Select s, ei, ki FROM cep_db_lite1_vc WHERE s IN ('d')")
ans= crsr.fetchall() 


filtered_data = ans[~np.isnan(ans["ki"])] 


dogData = np.array(filtered_data)
dogData.astype(float)
FdogData= dogData[:, [1,2]]
x, y = FdogData[:,0], FdogData[:,1]

如何解决此脚本?数周来我一直在为这个错误而苦苦挣扎!

1 个答案:

答案 0 :(得分:2)

  

TypeError:列表索引必须是整数或切片,而不是str

这意味着您不能使用str索引列表,只能使用整数和切片。这样,您可以在此行中找到它:

filtered_data = ans[~np.isnan(ans["ki"])]  

ans是一个列表,不能由字符串索引。

相关问题