2015-12-26 210 views
2

我想要一个简单的方法来访问指数相对于给定的指数在熊猫DataFrame。请参考下面其中绘制一个类似于一个numpy阵列的代码:熊猫数据帧相对索引

import numpy as np 
import pandas as pd 

# let's make a simple 2d matrix like array 
na_a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) 
print na_a 
print na_a[1][2] 
print na_a[1+1][2] # here I want to print the next value in the same column so I iterate the row by 1 

# now let's put this array into a pandas dataframe 
df_a = pd.DataFrame(na_a,index = ['1','2','3','4'], columns = ['A','B','C','D']) 
print df_a 
print df_a['C']['2'] 
# now how do I easily iterate the row by 1 to print the next value in the same column? 

这里是输出:

[[ 1 2 3 4] 
[ 5 6 7 8] 
[ 9 10 11 12] 
[13 14 15 16]] 
7 
11 
    A B C D 
1 1 2 3 4 
2 5 6 7 8 
3 9 10 11 12 
4 13 14 15 16 
7 

这应用于一般相对索引是可能的(不沿一个方向仅仅1 )。

+0

Pandas背后的一个想法是能够轻松地对数据执行批量操作并避免迭代的需要。你能否详细说明你想在更高层面上完成什么? – Windstorm1981

+0

为什么不使用基于整数的索引,即'iloc [2,2]'? – Alexander

+0

在最高级别上,这是一个缺点和十字架游戏(连续5次)。我决定在一个DataFrame中保存板子(主要是因为我是python的新手)。我的AI对手现在可以通过查找连续X的链来找到潜在的威胁。假设三个X的链条在F5,F6,F7。我的约定给出链的地址为F7,它的长度为3.如果AI想要放下O来阻止链,它必​​须到达地址F7,并将数字索引迭代1到F8。 –

回答

3

如果我理解正确,那么您要确定一个新的index标签相对于另一个index标签来选择一个新的row

pandas提供了pd.Index.get_loc()方法来检索标签的基于零的integerindex位置。一旦你的integer位置,你可以得到标签的任何偏移,并选择相应的新行:相应

start_index_label = '2' 
df['C'][start_index_label] 

7 

的整数型index

column C始于indexlabel'2'的价值7row标签'2'1

start_index_position = df.index.get_loc(start_index_label) 

1 

添加2去整数基于index位置3产量label4

next_relative_index_position = +2 
next_index = df.index[start_index_position + next_relative_index_position] 

4 

相应row15

df['C'][next_index] 

15 

希望这有助于。

+1

如果我的标签不是整数?也许我错过了DataFrame应该为我做的一点。如果我有一个DataFrame,其索引是在日历日期中的,我想在1991年7月23日到100天之后访问所有内容(无需知道100天后的日期)? –

+2

我已经使用'string'标签来说明如何在'label'和'index'之间来回选择;你也可以使用'datetime'。但是,你的问题是关于一个具体的例子。对于你之后介绍的游戏例子,你可能最好在幕后使用基于“整数”的索引,相应地翻译字段名称以便于算术。另请看看文档:http://pandas.pydata.org/pandas-docs/stable/indexing.html – Stefan