我想要一种简单的方法来访问与 Pandas 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)。
最佳答案
如果我理解正确,那么你想识别一个新的 index
标签相对于另一个 index
标签来选择一个新的 row
。
pandas
提供了pd.Index.get_loc()
方法来获取从零开始的integer
index
标签的位置。一旦你有了 integer
位置,你就可以获得任何偏移量的标签并相应地选择一个新行:
从 index
label
'2'
开始,C 列
中的值 7
>:
start_index_label = '2'
df['C'][start_index_label]
7
行
标签'2'
对应的基于整数的索引
为1
:
start_index_position = df.index.get_loc(start_index_label)
1
将 2
添加到基于整数的 index
位置 3
产生 label
4
:
next_relative_index_position = +2
next_index = df.index[start_index_position + next_relative_index_position]
4
与相应的行
值15
:
df['C'][next_index]
15
希望这对您有所帮助。
关于python - Pandas Dataframe 相对索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34471672/