如何 select Python 中数据框列中的所有可用索引

How to select all available indices in a dataframe column in Python

我有一个包含多个变量的数据框 df,其中包含许多不规则索引的条目。

让我们这样说:

        X  Y  
0    60.0  0   
1    63.0  10      
4    80.0  10             
5    46.0  1            
9    73.0  10

[5 rows x 2 columns]

现在,假设我有一个外部提供的索引列表,indices,例如:

indices = [0, 2, 4, 6, 9, 11]

如何 select df['X'] 的所有条目,这些条目是索引的一部分?我想要的输出是

        X  
0    60.0          
4    80.0                          
9    73.0 

如果我只是尝试打电话给 df['X'][indices],Python 理所当然地抱怨:

KeyError: '[2, 6, 11] not in index'

有没有简单的方法可以做到这一点?

您可以尝试将 df 的索引转换为新列,并使用 .isin():

过滤这些索引
# convert original indexes to new column
df["original_index"] = df.index
    
# filter based on list values
indices = [0, 2, 4, 6, 9, 11]
df[df["original_index"].isin(indices)]

输出:

    x   y   original_index
0   60  0   0
4   80  10  4
9   73  10  9

或者,您也可以使用 .reset_index(),这会将原始索引移动到新列,并且 re-index 索引:

# convert original indexes to new column and re-index
df.reset_index(inplace=True)


# filter based on list values
indices = [0, 2, 4, 6, 9, 11]
df[df["index"].isin(indices)]

输出:

  index x   y
0   0   60  0
2   4   80  10
4   9   73  10

使用Index.isin():

print(df.loc[df.index.isin(indices), 'X'])
0    60.0
4    80.0
9    73.0
Name: X, dtype: float64