pandas 熊猫中的简单 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/19045939/
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
Simple for loop in pandas
提问by Ashleigh Clayton
I have a simple indexing question with respect to pandas. I would like to make a simple for loop to go over numbers 1 to 5. I'm having trouble with pandas indexing in how to do this (although I'm sure its simple!)
我有一个关于Pandas的简单索引问题。我想做一个简单的 for 循环来遍历数字 1 到 5。我在如何执行此操作时遇到了Pandas索引(尽管我确定它很简单!)
My rough code:
我的粗略代码:
def averaged_rel_track(current_tracks, rel_values):
    current_tracks['rel_values']=rel_values
    current_tracks=current_tracks.set_index('candidate')
    #I would like this line to loop over numbers 1 to 5
    b_1= current_tracks.rel_values.loc['1']
What I have tried:
我尝试过的:
for i in range(1, 6):
    b=current_tracks.rel_values.iloc[i]
for i in range (1, 6):
    b = current_tracks.rel_values[i]
for i in range (1, 6):
   b=current_tracks.rel_values['i']
and various other similar variations (including .ix, .iloc, .loc)
以及其他各种类似的变体(包括.ix, .iloc, .loc)
回答by hans_meine
Your first try does not look too bad; I think you could use:
你的第一次尝试看起来还不错;我认为你可以使用:
for i in range(5):
    b = current_tracks.rel_values.iloc[i] # by standard 0-based sequence index
or
或者
for i in range(1, 6):
    b = current_tracks.rel_values.loc[i] # by 1-based track number
But you probably want to avoid 'for i in range(...)', which is not pythonic:
但是你可能想避免'for i in range(...)',这不是pythonic:
for b in current_tracks.rel_values.loc[1:5]: # or .iloc[:5]
    ...
Note that .loc[1:5] includesthe last index value, while .iloc does not. That's more intuitive than it sounds, since .iloc uses standard python indexing, while .loc supports any kind of application-specific indices, and it might not be possible to "increment" the end index in non-integer cases.
请注意, .loc[1:5]包含最后一个索引值,而 .iloc 不包含。这比听起来更直观,因为 .iloc 使用标准 python 索引,而 .loc 支持任何类型的特定于应用程序的索引,并且在非整数情况下可能无法“增加”结束索引。

