python - 获取满足某些条件的索引

标签 python pandas

在 Pandas 中,如何获取满足某些属性的条目的系列/数据框的索引列表?

以下返回一个Series对象

my_dataframe.loc[:,'some_column'] == 'some_value'

看起来像这样:

519     True
509    False
826    False
503    False
511    False
512    False
500    False
507    False
516     True
504    False
521    False
510    False
351    False
522    False
526    False
517    False
501    False

但我想要的是两个列表,一个是

[519, 516]

和一个与其余索引。我如何在 Pandas 中执行此操作?

最佳答案

In [8]: df = DataFrame(randn(10,2),columns=list('AB'))

In [9]: df
Out[9]: 
          A         B
0 -1.046978  1.561624
1 -0.264645  0.717171
2  0.112354 -2.084449
3 -1.243482 -1.183749
4  1.055667  0.532444
5 -1.295805  2.168225
6 -1.239725  0.969934
7 -0.354017  1.434943
8 -0.867560  0.810315
9  0.097698 -0.033039

In [10]: df.loc[:,'B'] > 0
Out[10]: 
0     True
1     True
2    False
3    False
4     True
5     True
6     True
7     True
8     True
9    False
Name: B, dtype: bool

In [14]: x = df.loc[:,'B'] > 0

Per Tom/Andy, much simpler 

In [33]: x[x].index
Out[33]: Int64Index([0, 1, 4, 5, 6, 7, 8], dtype=int64)

In [34]: x[~x].index
Out[34]: Int64Index([2, 3, 9], dtype=int64)

关于python - 获取满足某些条件的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17215682/

相关文章:

python - 在 pandas 中提取特定值后的文本

python - 如何使用 python 2.7 将字符串正确解析为字素簇?

pandas - 如何使用pandas查找列的最大值并按顺序排列它们?

python - Pandas 数据框 - 删除异常值

python - 在 pandas 中展平一个系列,即一个元素为列表的系列

python - 从 Django 管理命令显示任务进度

python - 在 Tkinter 的 PIL 中调整图片大小

python - 使用 python-social-auth 在数据库中预先注册用户

Pandas 数据帧到 Spark 数据帧 "Can not merge type error"

python - pandas fillna 按顺序一步一步