gpt4 book ai didi

python - + : 'int' and 'str' using Pandas mean 不支持的操作数类型

转载 作者:太空宇宙 更新时间:2023-11-03 13:56:10 24 4
gpt4 key购买 nike

当我尝试获取数据框的其中一列的平均值时,它显示错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

这是我的代码:

import pandas as pd

import numpy as np

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data"

df = pd.read_csv(url, header = None, )

headers = ["symboling","normalized-losses","make","fuel-type","aspiration","num-of-doors","body-style","drive-wheels","engine-location","wheel-base","lenght","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.columns = headers

df.replace('?',np.nan, inplace=True)

mean_val = df['normalized-losses'].mean()

print(mean_val)

最佳答案

您需要使用 pd.to_numeric() 将列数据类型转换为数字。如果您使用选项 errors='coerce',那么它会自动将非数字字符替换为 NaN

mean_val = pd.to_numeric(df['normalized-losses'], errors='coerce').mean()

print(mean_val)

> 122.0

关于python - + : 'int' and 'str' using Pandas mean 不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com