从我之前的问题开始:Get grouped informations from an array with Pandas
我有一个像这样的数据集,我想通过大熊猫获取此信息:对于每一天(按日分组),第二个值是“打开”,第二个值是“关闭”,最高值“高”的值和“低”的值的最小值以及体积的总和。
"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
在我之前的问题中,一个用户建议我使用它:
df.groupby('Date').agg({
'Close': 'last',
'Open': 'first',
'High': 'max',
'Low': 'min',
'Volume': 'sum'
})
但是现在我想将第二个元素用于Open,将倒数第二个用于Close。我该怎么办?
答案 0 :(得分:4)
您可以创建自定义函数,只有在第二个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