与我之前的问题previous question about pandas index tuples
相同如何访问索引中具有相同元组第二元素的df的所有行?
我有以下df继续到下一个日期。用同一个符号一起显示日期会很棒。
Open Close Day Change
Date Symbol
11-01-2018 AEDAUD 0.3470 0.3448 -0.0022
AEDCAD 0.3415 0.3408 -0.0007
AEDCHF 0.2663 0.2656 -0.0007
AEDDKK 1.6955 1.6838 -0.0117
AEDEUR 0.2277 0.2261 -0.0016
我在使用符号列中所有具有相同值的行时遇到问题。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print(pd.__version__)
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)
tuples = list(forex[['Date', 'Symbol']].itertuples(index=False, name=None))
forex.index = pd.MultiIndex.from_tuples(tuples, names=['Date', 'Symbol'])
forex_open_close = pd.DataFrame(np.array(forex[['Open','Close']]), index=forex.index)
forex_open_close.columns = ['Open', 'Close']
forex_open_close['Day Change'] = forex_open_close['Close'] - forex_open_close['Open']
print(forex_open_close.head())
答案 0 :(得分:1)
好的归功于ChuHo
以下代码解决了我的问题
idx = pd.IndexSlice
print(forex_open_close.loc[idx[:,['AUDARS']], :])
并提供此输出:
Open Close Day Change
Date Symbol
11-01-2018 AUDARS 14.6193 14.7489 0.1296
12-01-2018 AUDARS 14.7486 14.7758 0.0272