计算列表的每个子列表的列y的平均值

时间:2018-03-25 07:51:47

标签: python arrays python-3.x

我正在寻找一种方法来计算数组中count_num传递的最后x个值。我怎么能成功地做到这一点?

import gdax

public_client = gdax.PublicClient()
data = public_client.get_product_historic_rates('BTC-USD', 
                    start=None, end=None, granularity=None)
count_num = 5
for i in data:    
    index = [i][0][5]
    average = index[-count_num:]/count_num

这是打印出列表后它返回的内容

[1521965100, 8464.99, 8470, 8464.99, 8470, 1.8307073700000003]
[1521965040, 8462.29, 8465, 8462.29, 8465, 0.54772126]
[1521964980, 8462.28, 8462.29, 8462.28, 8462.29, 0.41895371]
[1521964920, 8462.28, 8475, 8475, 8462.29, 0.9895914299999999]
[1521964860, 8475, 8475.01, 8475.01, 8475, 0.07485000000000001]
[1521964800, 8471.91, 8480.93, 8471.91, 8475.01, 0.36869809000000003]
[1521964740, 8471.9, 8471.91, 8471.91, 8471.91, 0.18909909]
[1521964680, 8471.31, 8471.91, 8471.31, 8471.91, 0.0864]
[1521964620, 8471.31, 8480.46, 8480.46, 8471.31, 1.03771926]
[1521964560, 8481.64, 8490, 8489.99, 8481.64, 10.089637590000004]

以下是索引的示例输出,我试图找到它的平均值。

6.64786609
1.6042117200000003
1.58478991
7.936872120000001
2.6782738599999987
1.8307073700000003
0.54772126
0.41895371
0.9895914299999999
0.07485000000000001
0.36869809000000003
0.18909909

2 个答案:

答案 0 :(得分:1)

这就是你需要的:

average = sum(row[-1] for row in data[-count_num:]) / count_num
pint(average)
#2.354310806000001

答案 1 :(得分:1)

尝试使用numpy:

import numpy as np

data = [[1,2,3,4],[2,3,4,5],[3,4,5,6]]

tmp=np.zeros(len(data))
x=0

for i in data: 
   tmp[x]=data[x][-1]
   x=x+1

average=np.mean(tmp)
print(average)
#5.0