Why can't I search for a row in a pandas df using a date as part of a tuple index?

大兔子大兔子 提交于 2020-01-06 06:59:35

问题


I am trying to search a pandas df I made which has a tuple as an index. The first part of the tuple is a date and the second part is a forex pair. I've tried a few things but I can't seem to search using a date-formatted string as part of a tuple with .loc or .ix

My df looks like this:

                        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

Here is the complete code :

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')])

How do I get the row which has index ('11-01-2018', 'GBPUSD') ?


回答1:


I would recommend using the Pandas multiIndex. In your case you could do the following:

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']



回答2:


Can you try putting the tuple in a list using brackets?

Like this:

print(forex_open_close.ix[[('11-01-2018', 'GBPUSD')]])


来源:https://stackoverflow.com/questions/49157349/why-cant-i-search-for-a-row-in-a-pandas-df-using-a-date-as-part-of-a-tuple-inde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!