Python 统计包 mean() 从 Pandas 数据框中给出错误答案

我正在使用 Python 3.6,试图获取 Pandas 数据帧(pandas 版本 0.23.4)一行的子集中某些值的平均值。我使用 .loc[] 获取值,然后尝试使用来自 python 统计包的 mean() 获取它们的平均值,如下所示:


import statistics as st

rows = ['row1','row2','row3']

somelist = []

for i in rows:

    a = df.loc[i,"Q1":"Q7"]

    somelist.append(st.mean(a))

我最终得到的答案没有任何小数位。如果我手动将项目 Q1:Q7 的答案写入列表,结果如下:


a = st.mean([2,3,4,4,2,6,5])

print(a)

Out: 3.7142857142857144

但是,如果该序列是我从数据框中提取的序列,我会得到一个没有小数位的平均值,如下所示:


a = st.mean(df.loc[i,"Q1":"Q7"])

Out: 3

显然这是因为它认为它是一个 numpy.int64 而不是一个浮点数。即使我将数据帧中的切片转换为列表,也会发生这种情况,如下所示:


a = st.mean(list(df.loc[i,"Q1":"Q7"]))

Out: 3

奇怪的是,如果我使用 .mean() 就不会发生这种情况:


a = df.loc[i,"Q1":"Q7"].mean()

Out: 3.7142857142857144

我仔细检查了 st.stdev() 方法,它似乎工作正常。这是怎么回事?为什么要自动打印出平均值的整数?谢谢!


烙印99
浏览 1036回答 2
2回答

米脂

statistics.mean将输出转换为与输入相同的类型。如果输入值都为 ,例如numpy.int64,则结果将转换为numpy.int64。这是statistics.meanPython 3.6.7 中的源代码:def mean(data):&nbsp; &nbsp; """Return the sample arithmetic mean of data.&nbsp; &nbsp; >>> mean([1, 2, 3, 4, 4])&nbsp; &nbsp; 2.8&nbsp; &nbsp; >>> from fractions import Fraction as F&nbsp; &nbsp; >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])&nbsp; &nbsp; Fraction(13, 21)&nbsp; &nbsp; >>> from decimal import Decimal as D&nbsp; &nbsp; >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])&nbsp; &nbsp; Decimal('0.5625')&nbsp; &nbsp; If ``data`` is empty, StatisticsError will be raised.&nbsp; &nbsp; """&nbsp; &nbsp; if iter(data) is data:&nbsp; &nbsp; &nbsp; &nbsp; data = list(data)&nbsp; &nbsp; n = len(data)&nbsp; &nbsp; if n < 1:&nbsp; &nbsp; &nbsp; &nbsp; raise StatisticsError('mean requires at least one data point')&nbsp; &nbsp; T, total, count = _sum(data)&nbsp; &nbsp; assert count == n&nbsp; &nbsp; return _convert(total/n, T)请注意,total/n在返回之前转换为输入类型。为避免这种情况,您可以将输入转换为浮点数,然后再将其传递给statistics.mean.

一只甜甜圈

我认为你在做错的事情。尝试为您要经过的每一行打印 a 以及列表中的附加平均值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python