Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

python - TypeError: object of type 'numpy.float64' has no len() when printing the regression coefficient of the first column in dataframe

I want to find the number of regression coefficients in the first column of my dataframe. My code raised

TypeError: object of type 'numpy.float64' has no len()
from sklearn.linear_model import LinearRegression

df = pd.read_csv("master.csv")    
# Drop redundant features
X = df.drop(['suicides/100k pop', 'country-year', 'suicides_no'], axis=1)
y = df['suicides/100k pop']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression(n_jobs=4, normalize=True, copy_X=True)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

print(f"There are {len(model.coef_[0])} regression coefficients:")
print(model.coef_[0])

X_train

print(type(X_train))

> <class 'scipy.sparse.csr.csr_matrix'>

y_train

print(type(y_train))
> <class 'pandas.core.series.Series'>

Traceback:

> --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call
> last) /tmp/ipykernel_6232/341058392.py in <module>
>       1 # Check number of and values of coefficients
> ----> 2 print(f"There are {len(model.coef_[0])} regression coefficients:")
>       3 print(model.coef_[0])
> 
> TypeError: object of type 'numpy.float64' has no len()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you are using [0] you are "calling" a specific value. It is a number therefore it has no len() which is a string function.

If you want to print out the len use:

len(model.coef_)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...