Skip to main content
 首页 » 编程设计

python之如何获取满足 pandas 中某些条件的列索引

2024年10月24日10jillzhang

我有以下内容:

x = pd.DataFrame({'a':[1,5,5], 'b':[7,0,7]}) 

对于每一行,我想获取满足其值大于某个值的第一列的索引,比方说大于 4.

本例中答案为1,(对应第一行数值7的索引)和0(对应第二行数值5的索引),1(对应索引第三行中的值 5)。 这意味着答案是 [1,0,0]。

我用 apply 方法试过了:

def get_values_from_row(row, th=0.9): 
    """Get a list of column names that meet some condition that their values are larger than a threshold. 
 
Args: 
    row(pd.DataFrame): a row. 
    th(float): the threshold. 
 
Returns: 
    string. contains the columns that it's value met the condition. 
""" 
return row[row > th].index.tolist()[0]  

它有效,但我有一个大数据集,而且速度很慢。 什么是更好的选择。

请您参考如下方法:

我想你需要first_valid_index与 get_loc :

print (x[x > 4]) 
     a    b 
0  NaN  7.0 
1  5.0  NaN 
2  7.0  5.0 
 
print (x[x > 4].apply(lambda x: x.index.get_loc(x.first_valid_index()), axis=1)) 
0    1 
1    0 
2    0 
dtype: int64