2015-12-26 216 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