在有字符串的情况下求平均值 Pandas

Finding Mean Value Pandas While Having String

我有一个 20*5 的数据 table,我想找到其中一列(价格列)的平均值。我知道我必须使用这种方法来求平均值

mean= df["price"].mean()

问题是在我的数据文件中,价格不是整数,而是字符串,并且所有这些都是以这种格式编写的 e.x。(2000 美元不仅仅是 2000)。如何从数字中去除这些货币,然后求出数字的平均值?(货币都是一样的)

df['price'].str.replace('dollars', '').astype('float').mean()

先尝试规范化您的数据,

df["price"] = df["price"].apply(lambda x: float(x.replace("dollars", "")))

我假设价格是5000dollars这样存储的,如果有其他异常,可以换成空值。

或者如果您不想更新此列条目,您可以创建一个新列并将该列用作平均值,

df["new_price"] = df["price"].apply(lambda x: float(x.replace("dollars", "")))