问题在最后,在bold。但首先,让我们设置一些数据:
import numpy as np
import pandas as pd
from itertools import product
np.random.seed(1)
team_names = ['Yankees', 'Mets', 'Dodgers']
jersey_numbers = [35, 71, 84]
game_numbers = [1, 2]
observer_names = ['Bill', 'John', 'Ralph']
observation_types = ['Speed', 'Strength']
row_indices = list(product(team_names, jersey_numbers, game_numbers, observer_names, observation_types))
observation_values = np.random.randn(len(row_indices))
tns, jns, gns, ons, ots = zip(*row_indices)
data = pd.DataFrame({'team': tns, 'jersey': jns, 'game': gns, 'observer': ons, 'obstype': ots, 'value': observation_values})
data = data.set_index(['team', 'jersey', 'game', 'observer', 'obstype'])
data = data.unstack(['observer', 'obstype'])
data.columns = data.columns.droplevel(0)
this gives:
我想提取这个 DataFrame 的子集以供后续分析。假设我想切掉其中的行jersey
号码是 71。我不太喜欢使用这个想法xs
去做这个。当你通过做横截面时xs
您将丢失所选的列。如果我运行:
data.xs(71, axis=0, level='jersey')
然后我找回正确的行,但我失去了jersey
column.
Also, xs
对于我想要一些不同值的情况,这似乎不是一个很好的解决方案jersey
柱子。我认为找到了一个更好的解决方案here https://stackoverflow.com/questions/11941492/selecting-rows-from-a-pandas-dataframe-with-a-compound-hierarchical-index#comment15917600_11942697:
data[[j in [71, 84] for t, j, g in data.index]]
您甚至可以过滤球衣和球队的组合:
data[[j in [71, 84] and t in ['Dodgers', 'Mets'] for t, j, g in data.index]]
Nice!
所以问题是:我怎样才能做类似的事情来选择列的子集。例如,假设我只想要代表 Ralph 数据的列。我怎样才能做到这一点而不使用xs
?或者如果我只想要包含以下内容的列怎么办observer in ['John', 'Ralph']
?再说一次,我真的更喜欢一个在结果中保留行和列索引的所有级别的解决方案......就像上面的布尔索引示例一样。
我可以做我想做的事,甚至可以组合行索引和列索引中的选择。但我发现的唯一解决方案涉及一些真正的体操:
data[[j in [71, 84] and t in ['Dodgers', 'Mets'] for t, j, g in data.index]]\
.T[[obs in ['John', 'Ralph'] for obs, obstype in data.columns]].T
因此第二个问题是:有没有更紧凑的方法来完成我上面所做的事情?