我已经设置了这样的代码:
import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'],
['aaa', 'bbb', 'ccc', 'ccc', 'ddd', 'eee', 'eee', 'eee' ]]
tuples = zip(*arrays)
index = pd.MultiIndex.from_tuples(tuples, names=['A', 'B', 'C'])
df = pd.DataFrame(np.random.randn(8, 4), index=index)
df
Out[161]:
0 1 2 3
A B C
bar one aaa 0.682220 -0.598889 -0.600635 -0.488069
two bbb -0.134557 1.614224 -0.191303 0.073813
baz one ccc -1.006877 -0.137264 -0.319274 1.465952
two ccc 0.107222 0.358468 0.165108 -0.258715
foo one ddd 0.360562 1.759095 -1.385394 -0.646850
two eee -1.113520 0.221483 2.226704 -0.994636
qux one eee -0.609271 -0.888330 0.824189 1.772536
two eee -0.008346 -0.688091 0.263303 1.242485
Run Code Online (Sandbox Code Playgroud)
我想找到基于标准组合与A,B和C组匹配的行.
例如在sql术语中:select*其中A in('foo','qux')和C ='eee'
我可以用ix实现这一点吗?例如:
df.ix(['foo', 'qux'],:,'eee')
Run Code Online (Sandbox Code Playgroud)
对于非常大的数据集,实现此目的的唯一方法是什么?
(我目前正在使用pandas 0.7,但如果绝对必要可以升级)
我将编写一个函数来执行此类操作:
import numpy as np
def ms(df, *args):
idx = df.index
for i, values in enumerate(args):
if values is not None:
if np.isscalar(values):
values = [values]
idx = idx.reindex(values, level=i)[0]
return df.ix[idx]
Run Code Online (Sandbox Code Playgroud)
然后你可以很容易地做到:
ms(df, ['foo', 'qux'], None, "eee")
Run Code Online (Sandbox Code Playgroud)