我认为您需要get_loc 来获取MultiIndex 的位置,然后通过iloc 选择:
d = '05-Jun-2017 09:00'
s = 'AAL'
pos = df.index.get_loc((s,d))
df1 = df.iloc[pos-1:pos + 11]
print (df1)
但如果t 是第一个值或10 最后一个值,则会出现问题:
df1 = df.iloc[max(pos-1,0): min(pos+11,len(df.index))]
示例:
print (df)
Open High Low Close Volume
Symbol Date
AAL 05-Jun-2017 08:00 1.1801 1.1819 1.1801 1.1817 4
05-Jun-2017 09:00 1.1817 1.1818 1.1804 1.1814 18
05-Jun-2017 10:00 1.1817 1.1817 1.1802 1.1806 12
05-Jun-2017 11:00 1.1807 1.1815 1.1795 1.1808 26
05-Jun-2017 12:00 1.1803 1.1806 1.1790 1.1806 4
05-Jun-2017 13:00 1.1801 1.1801 1.1779 1.1786 23
05-Jun-2017 14:00 1.1795 1.1801 1.1776 1.1788 28
05-Jun-2017 15:00 1.1793 1.1795 1.1782 1.1789 10
05-Jun-2017 16:00 1.1780 1.1792 1.1776 1.1792 12
05-Jun-2017 17:00 1.1788 1.1792 1.1788 1.1791 4
d = '05-Jun-2017 09:00'
s = 'AAL'
pos = df.index.get_loc((s,d))
df1 = df.iloc[max(pos-1,0): min(pos+10,len(df.index))]
print (df1)
Open High Low Close Volume
Symbol Date
AAL 05-Jun-2017 08:00 1.1801 1.1819 1.1801 1.1817 4
05-Jun-2017 09:00 1.1817 1.1818 1.1804 1.1814 18
05-Jun-2017 10:00 1.1817 1.1817 1.1802 1.1806 12
05-Jun-2017 11:00 1.1807 1.1815 1.1795 1.1808 26
05-Jun-2017 12:00 1.1803 1.1806 1.1790 1.1806 4
05-Jun-2017 13:00 1.1801 1.1801 1.1779 1.1786 23
05-Jun-2017 14:00 1.1795 1.1801 1.1776 1.1788 28
05-Jun-2017 15:00 1.1793 1.1795 1.1782 1.1789 10
05-Jun-2017 16:00 1.1780 1.1792 1.1776 1.1792 12
05-Jun-2017 17:00 1.1788 1.1792 1.1788 1.1791 4
不可能选择上一行,因为时间戳t 是索引的第一个值:
d = '05-Jun-2017 08:00'
s = 'AAL'
pos = df.index.get_loc((s,d))
df1 = df.iloc[max(pos-1,0): min(pos+10,len(df.index))]
print (df1)
Open High Low Close Volume
Symbol Date
AAL 05-Jun-2017 08:00 1.1801 1.1819 1.1801 1.1817 4
05-Jun-2017 09:00 1.1817 1.1818 1.1804 1.1814 18
05-Jun-2017 10:00 1.1817 1.1817 1.1802 1.1806 12
05-Jun-2017 11:00 1.1807 1.1815 1.1795 1.1808 26
05-Jun-2017 12:00 1.1803 1.1806 1.1790 1.1806 4
05-Jun-2017 13:00 1.1801 1.1801 1.1779 1.1786 23
05-Jun-2017 14:00 1.1795 1.1801 1.1776 1.1788 28
05-Jun-2017 15:00 1.1793 1.1795 1.1782 1.1789 10
05-Jun-2017 16:00 1.1780 1.1792 1.1776 1.1792 12
05-Jun-2017 17:00 1.1788 1.1792 1.1788 1.1791 4
不可能选择下一行的所有 10 个,因为 t 是后面的 3.rd 值:
d = '05-Jun-2017 15:00'
s = 'AAL'
pos = df.index.get_loc((s,d))
df1 = df.iloc[max(pos-1,0): min(pos+10,len(df.index))]
print (df1)
Open High Low Close Volume
Symbol Date
AAL 05-Jun-2017 14:00 1.1795 1.1801 1.1776 1.1788 28
05-Jun-2017 15:00 1.1793 1.1795 1.1782 1.1789 10
05-Jun-2017 16:00 1.1780 1.1792 1.1776 1.1792 12
05-Jun-2017 17:00 1.1788 1.1792 1.1788 1.1791 4