简体   繁体   English

python中字典数据的均值和中位数如何计算

[英]How calculate mean and median of dictionary data in python

I am appeding dictinary values but how calculate median of this data?我正在应用字典值,但如何计算这些数据的中值? I have another method for calculate mean that works but median occurs error...我有另一种计算均值的方法有效但中位数出现错误...

arr = []
for i in range(n):
     data =  getValues() #[{450: 37, 451: 59, 452: 18, 453: 88, 454: 52},{450: 40, 451: 27, 452: 26, 453: 15, 454: 20},{450: 16, 451: 12, 452: 12, 453: 13, 454: 13},{450: 7, 451: 5, 452: 6, 453: 5, 454: 5}]
     od = collections.OrderedDict(sorted(data.items()))
     arr.append(od )

medianArr = np.median(arr, axis=0)
meanArr = np.mean(arr)
np.savetxt("dataMedian.txt", medianArr , fmt="%s", delimiter=",")   #only values, without keys
np.savetxt("dataMean.txt", meanArr , fmt="%s", delimiter=",")  #only values, without keys

my working method for mean:我的平均工作方法:

arr2d = []
for i in range(n):
    count += 1
    data =  getValues() #[{450: 37, 451: 59, 452: 18, 453: 88, 454: 52},{450: 40, 451: 27, 452: 26, 453: 15, 454: 20},{450: 16, 451: 12, 4652: 12, 453: 13, 454: 13},{450: 7, 451: 5, 452: 6, 453: 5, 454: 5}]
    od = collections.OrderedDict(sorted(data.items()))
    arr = []
    for k, v in od.items():
        arr.append(v/count)
    arr2d.append(arr)

np.savetxt("dataMean.txt", arr2d, fmt="%s", delimiter=",") #ok

In order to work with NumPy utilities, you can stack your dictionaries' values in a single array:为了使用 NumPy 实用程序,您可以将字典的值堆叠在一个数组中:

>>> arr = np.stack([list(d.values()) for d in data])
array([[37, 59, 18, 88, 52],
       [40, 27, 26, 15, 20],
       [16, 12, 12, 13, 13],
       [ 7,  5,  6,  5,  5]])

Then, assuming you're looking to compute the statistics of your data per dictionary, you can do:然后,假设您要计算每个字典的数据统计信息,您可以执行以下操作:

>>> np.mean(arr, 1), np.median(arr, 1)
(array([50.8, 25.6, 13.2,  5.6]), array([52., 26., 13.,  5.]))

You can of course compute the global mean and median by removing the axis option on both calls.您当然可以通过删除两个调用中的轴选项来计算全局均值和中位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM