Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对熊猫中的数据帧重新采样并应用加权平均值?_Python_Pandas_Numpy - Fatal编程技术网

Python 如何对熊猫中的数据帧重新采样并应用加权平均值?

Python 如何对熊猫中的数据帧重新采样并应用加权平均值?,python,pandas,numpy,Python,Pandas,Numpy,我有一个按时间索引的数据框,有两列:price和quantity 我想构建一个新的系列,它是15分钟间隔的加权平均价格,按数量加权 这是我的数据帧的头部: price quantity ts 2020-06-10 15:56:34+00:00 203.0 400 2020-06-10 15:57:10+00:00 203.0 1300 2

我有一个按时间索引的数据框,有两列:
price
quantity

我想构建一个新的系列,它是15分钟间隔的加权平均价格,按数量加权

这是我的数据帧的头部:

                          price  quantity
ts                                        
2020-06-10 15:56:34+00:00  203.0       400
2020-06-10 15:57:10+00:00  203.0      1300
2020-06-10 15:57:11+00:00  203.0      1100
2020-06-10 15:57:13+00:00  203.0      3000
2020-06-10 15:57:14+00:00  203.0       700
以下是我最好的尝试:

def重采样方法(x): 返回np.平均值(x.价格,权重=x.数量) df.重采样(“15T”)。应用(重采样法) 虽然上面的代码表达了我的意图(我相信),但我得到了以下错误:

Exception has occurred: AttributeError
'Series' object has no attribute 'price'

正如@Scott Boston在一篇评论中指出的,当使用
重采样
时,两列不能同时访问。一个技巧是将列数量附加到索引中,因为每个列都可以访问索引

# note I used '1T' instead of 15T like you but simple change in the method
dfr = (df.set_index('quantity', append=True)
         .resample('1T', level=0) # the datetime index is the level=0 
         .apply(lambda x: np.average(x, weights=x.index.get_level_values(1))) #quantity is on level=1
      )
print (dfr) #result not really interesting here it works
                           price
ts                              
2020-06-10 15:56:00+00:00  203.0
2020-06-10 15:57:00+00:00  203.0

正如@Scott Boston在一篇评论中指出的,当使用
重采样
时,两列不能同时访问。一个技巧是将列数量附加到索引中,因为每个列都可以访问索引

# note I used '1T' instead of 15T like you but simple change in the method
dfr = (df.set_index('quantity', append=True)
         .resample('1T', level=0) # the datetime index is the level=0 
         .apply(lambda x: np.average(x, weights=x.index.get_level_values(1))) #quantity is on level=1
      )
print (dfr) #result not really interesting here it works
                           price
ts                              
2020-06-10 15:56:00+00:00  203.0
2020-06-10 15:57:00+00:00  203.0

使用“应用”时,默认轴位于列上,因此每次应用访问每列。因此,当调用“价格”列时,“数量”列不可用。您需要做的是计算每行加权价格,然后在该加权价格列上重新采样15T。当您使用apply时,默认轴位于列上,因此apply一次访问每列。因此,当调用“价格”列时,“数量”列不可用。你需要做的是计算每行的加权价格,然后在加权价格列上重新取样15吨。