简体   繁体   English

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

[英]Calculate the average of column y for each sublist of a list

I am looking for a way to calculate the last x values passed by count_num in the array. 我正在寻找一种计算数组中count_num传递的最后x个值的方法。 How can I do that successfully? 我怎样才能成功做到这一点?

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

Here is what it returns once I print out the list 这是我打印出列表后返回的内容

[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]

Here is a sample output for index which I am trying to find the average for. 这是索引的样本输出,我正在尝试查找其平均值。

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

Here's what you need: 这是您需要的:

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

Try with numpy: 尝试使用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

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

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