[英]Select a specific row from a multiindex dataframe in pandas
I would like to select the last row from a multiindex dataframe and append to a dict of buy and sell signals.我想从多索引数据框中选择最后一行并附加到买卖信号的字典中。 For example, given the multiindex dataframe below:
例如,给定下面的多索引数据框:
enter image description here在此处输入图像描述
I would like to select the last row indexed (HK.00700 and 2022-06-28 10:39:00), and add to the dict as follows while keeping the last row's multiindices:我想选择索引的最后一行(HK.00700 和 2022-06-28 10:39:00),并按如下方式添加到字典中,同时保留最后一行的多索引:
enter image description here在此处输入图像描述
The indices in the second pic are slightly different, but the idea is the same.第二张图片中的索引略有不同,但想法是相同的。
Reproduce your data重现您的数据
level = [['HK.00700'],[pd.Timestamp('2022-06-28 10:38:00'),pd.Timestamp('2022-06-28 10:39:00')]]
level_index = pd.MultiIndex.from_product(level, names=['code','time_key'])
transaction = {
'open':[360.6, 360.8],
'close':[360.6, 361.4],
'high':[360.8, 361.4],
'low':[360.4, 360.4],
'volume':[72500, 116300],
'upper_band':[360.906089, 361.180835],
'lower_band':[357.873911, 357.719165]
}
df = pd.DataFrame(data=transaction, index=level_index)
df
It is easy if you only want to select the last row,如果您只想选择最后一行,这很容易,
df.tail(1)
Turn it into dict把它变成字典
df.tail(1).reset_index().loc[0].to_dict()
### Output
{'code': 'HK.00700',
'time_key': Timestamp('2022-06-28 10:39:00'),
'open': 360.8,
'close': 361.4,
'high': 361.4,
'low': 360.4,
'volume': 116300,
'upper_band': 361.180835,
'lower_band': 357.719165}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.