pandas 循环遍历一列熊猫时获取索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41070549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get index when looping through one column of pandas
提问by Jeff Saltfist
I have a simple dataframe:
我有一个简单的数据框:
index, a, y 0 , 1, 2 1 , 4, 6 2 , 5, 8
索引, a, y 0 , 1, 2 1 , 4, 6 2 , 5, 8
I want to loop through the "a" column, and print out its index for a specific value.
我想遍历“a”列,并打印出特定值的索引。
for x in df.a:
if x == 4:
print ("Index of that row")
What syntax should I use to obtain the index value when the for loop hits the specific value in the "a" column that I am seeking?
当 for 循环遇到我正在寻找的“a”列中的特定值时,我应该使用什么语法来获取索引值?
Thank You
谢谢你
回答by ayhan
A series is like a dictionary, so you can use the .iteritems
method:
一个系列就像一本字典,所以你可以使用这个.iteritems
方法:
for idx, x in df['a'].iteritems():
if x==4:
print('Index of that row: {}'.format(idx))
回答by Demetri Pananos
Use
用
df[df.a==4].index.values
to get an array of those indices
获取这些索引的数组