从大熊猫多重子集获取索引

时间:2018-08-20 09:42:36

标签: python pandas numpy indexing multi-index

给出此pandas.core.frame.DataFrame示例:

        col
0   2   0
    0   1
    3   1

我想获取col为1的那些索引:

df[df['col']==1]

预期结果将是向量(0,3)

2 个答案:

答案 0 :(得分:2)

您可以使用NumPy创建索引数组,然后过滤第二个索引:

import numpy as np

df = pd.DataFrame({'col': [0, 1, 1]},
                  index=pd.MultiIndex.from_tuples([(0, 2), (0, 0), (0, 3)]))

#      col
# 0 2    0
#   0    1
#   3    1

idx = np.array(df[df['col'] == 1].index.tolist())

# array([[0, 0],
#        [0, 3]])

res = idx[:, 1]

# array([0, 3])

答案 1 :(得分:1)

这可能会达到目的:

import pandas as pd

d = {'base':[2,0,3],'col':[0,1,1]}
df = pd.DataFrame(data=d)
col_is_1 = df['col'] == 1
df_temp = df[col_is_1]
matrix = df_temp.values
vec = matrix[:,0]
print(vec)

按预期返回[0,3]