我正在尝试搜索我制作的pandas df,其中有一个元组作为索引。元组的第一部分是日期,第二部分是外汇对。我尝试过一些东西,但我似乎无法使用日期格式的字符串作为元组的一部分进行搜索,使用.loc或.ix
我的df看起来像这样:
Open Close
(11-01-2018, AEDAUD) 0.3470 0.3448
(11-01-2018, AEDCAD) 0.3415 0.3408
(11-01-2018, AEDCHF) 0.2663 0.2656
(11-01-2018, AEDDKK) 1.6955 1.6838
(11-01-2018, AEDEUR) 0.2277 0.2261
以下是完整的代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
forex_11 = pd.read_csv('FOREX_20180111.csv', sep=',', parse_dates=['Date'])
forex_12 = pd.read_csv('FOREX_20180112.csv', sep=',', parse_dates=['Date'])
time_format = '%d-%m-%Y'
forex = forex_11.append(forex_12, ignore_index=False)
forex['Date'] = forex['Date'].dt.strftime(time_format)
GBP = forex[forex['Symbol'] == "GBPUSD"]
forex.index = list(forex[['Date', 'Symbol']].itertuples(index=False, name=None))
forex_open_close = pd.DataFrame(np.array(forex[['Open','Close']]), index=forex.index)
forex_open_close.columns = ['Open', 'Close']
print(forex_open_close.head())
print(forex_open_close.ix[('11-01-2018', 'GBPUSD')])
如何获得具有索引的行('11 -01-2018','GBPUSD')?
答案 0 :(得分:2)
您可以尝试使用括号将元组放入列表中吗?
像这样:
print(forex_open_close.ix[[('11-01-2018', 'GBPUSD')]])
答案 1 :(得分:1)
我建议使用Pandas multiIndex。在您的情况下,您可以执行以下操作:
tuples = list(data[['Date', 'Symbol']].itertuples(index=False, name=None))
data.index = pd.MultiIndex.from_tuples(tuples, names=['Date', 'Symbol'])
# And then to index
data.loc['2018-01-11', 'AEDCAD']