import pandas as pd
import matplotlib.pyplot as plt
eurusd = pd.read_csv("G:\Kuliah python\EURUSD_M15.csv",sep="\t")
print(eurusd.loc['2020-04-03 21:15'])
显示错误:
KeyError: '2020-04-03 21:15'
<table><tbody><tr><th><th>Time</th><th>Open</th><th>High</th><th>Low</th><th>Close</th><th>Volume</th><th> </th></tr><tr><td>0</td><td>2020-04-03 21:00:00</td><td>1.07893</td><td>1.07936</td><td>1.07839</td><td>1.07868</td><td>4380</td></tr><tr><td>1</td><td>2020-04-03 21:15:00</td><td>1.07867</td><td>1.07943</td><td>1.07831</td><td>1.07889</td><td>4860</td></tr><tr><td>2</td><td>2020-04-03 21:30:00</td><td>1.07888</td><td>1.07908</td><td>1.07762</td><td>1.07783</td><td>4022</td></tr><tr><td>3</td><td>2020-04-03 21:45:00</td><td>1.07782</td><td>1.08059</td><td>1.07727</td><td>1.07975</td><td>6816</td></tr><tr><td>4</td><td>2020-04-03 22:00:00</td><td>1.07975</td><td>1.08093</td><td>1.07920</td><td>1.08059</td><td>582</td></tr></tbody></table>
答案 0 :(得分:0)
我将尝试:将第一列设置为索引,您的.loc []索引将正常工作。
eurusd = pd.DataFrame(
[['2020-04-03 21:00:00', 1.07893, 1.07936, 1.07839, 1.07868, 4380],
['2020-04-03 21:15:00', 1.07867, 1.07943, 1.07831, 1.07889, 4860],
['2020-04-03 21:30:00', 1.07888, 1.07908, 1.07762, 1.07783, 4022],
['2020-04-03 21:45:00', 1.07782, 1.08059, 1.07727, 1.07975, 6816],
['2020-04-03 22:00:00', 1.07975, 1.08093, 1.07920, 1.08059, 582]]
).set_index(0)
eurusd.loc['2020-04-03 21:15:00']
1 1.07867
2 1.07943
3 1.07831
4 1.07889
5 4860.00000
Name: 2020-04-03 21:15:00, dtype: float64
您可以通过将索引设置为DateTimeIndex来进一步改善这一点:
eurusd.index = pd.to_datetime(eurusd.index)
这允许“部分字符串索引”之类的
eurusd.loc['2020-04-03 21']
2020-04-03 21:00:00 1.07893 1.07936 1.07839 1.07868 4380
2020-04-03 21:15:00 1.07867 1.07943 1.07831 1.07889 4860
2020-04-03 21:30:00 1.07888 1.07908 1.07762 1.07783 4022
2020-04-03 21:45:00 1.07782 1.08059 1.07727 1.07975 6816
为您提供21:00和22:00之间的所有行(不包括)。