IBM Data Science:float()参数必须是字符串或数字,而不是“方法”

2024-04-28 04:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行以下代码:

#calculate the mean vaule for "stroke" column
avg_stroke=df['stroke'].astype('float').mean(axis=0)
print("Average of stroke:", avg_stroke)

但是,我不断遇到以下错误:

float() argument must be a string or a number, not 'method'` on this code.

我在脚本的不同部分使用了相同的代码结构,并实现了一个很好的干净的意思:

#Write your code below and press Shift+Enter to execute 
avg_norm_loss = df["normalized-losses"].astype("float").mean(axis=0)
print("Average of normalized-losses:", avg_norm_loss)

我已经从这些SE答案中排除了任何建议/答案:


Tags: or代码numberdfstringstrokenotbe
1条回答
网友
1楼 · 发布于 2024-04-28 04:18:18

您知道该列中存在值为“”的字符串吗? 你必须先移除它。除此之外,代码对我有效

import pandas as pd
url = r"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/auto.csv"
col_names = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","body-style", "drive-wheels","engine-location","wheel-base", "length","width","height","curb-weight","engine-type", "num-of-cylinders", "engine-size","fuel-system","bore","stroke","compression-ratio","horsepower", "peak-rpm","city-mpg","highway-mpg","price"]
df = pd.read_csv(url, names=col_names)

df = df[df['stroke']!="?"]

avg_stroke = df['stroke'].astype('float').mean(axis=0)
print("Average of stroke:", avg_stroke)
#out: Average of stroke: 3.255422885572139

相关问题 更多 >