简体   繁体   English

带聚合的 Pandas groupby

[英]Pandas groupby with aggregation

Starting from my previous question: Get grouped informations from an array with Pandas从我之前的问题开始: 使用 Pandas 从数组中获取分组信息

I have a Dataset structured like this and I want to get this information with pandas: for each day (so grouped day by day) get the second value of "Open", second-last value of "Close", Highest value of "High" and Lower value of "Low", and sum of Volume.我有一个这样结构的数据集,我想用 Pandas 获取这些信息:每天(按天分组)获取“打开”的第二个值,“关闭”的倒数第二个值,“高”的最高值" 和 "Low" 的下限值,以及 Volume 的总和。

"Date","Time","Open","High","Low","Close","Up","Down","Volume"
01/03/2000,00:05,1481.50,1481.50,1481.00,1481.00,2,0,0.00
01/03/2000,00:10,1480.75,1480.75,1480.75,1480.75,1,0,1.00
01/03/2000,00:20,1480.50,1480.50,1480.50,1480.50,1,0,1.00
[...]
03/01/2018,11:05,2717.25,2718.00,2708.50,2709.25,9935,15371,25306.00
03/01/2018,11:10,2709.25,2711.75,2706.50,2709.50,8388,8234,16622.00
03/01/2018,11:15,2709.25,2711.50,2708.25,2709.50,4738,4703,9441.00
03/01/2018,11:20,2709.25,2709.50,2706.00,2707.25,3609,4685,8294.00

In my previous question an user suggest me to use this:在我之前的问题中,用户建议我使用这个:

df.groupby('Date').agg({
'Close': 'last',
'Open': 'first',
'High': 'max',
'Low': 'min',
'Volume': 'sum'

}) })

But now I want to take the second element for Open and second-last for Close.但现在我想为 Open 取第二个元素,为 Close 取倒数第二个元素。 How can I do this?我怎样才能做到这一点?

You can create custom functions, only necessary specify output if second val not exist, eg NaN or first values x.iat[0] :您可以创建自定义函数,仅当第二个 val 不存在时才需要指定输出,例如NaN或第一个值x.iat[0]

def second(x):
    return x.iat[1] if len(x) > 1 else np.nan

def secondLast(x):
    return x.iat[-2] if len(x) > 1 else np.nan

df1 = df.groupby('Date').agg({
'Close': secondLast,
'Open': second,
'High': 'max',
'Low': 'min',
'Volume': 'sum'

})

print (df1)
              Close     Open    High     Low   Volume
Date                                                 
01/03/2000  1480.75  1480.75  1481.5  1480.5      2.0
03/01/2018  2709.50  2709.25  2718.0  2706.0  59663.0

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

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