Pandas数据帧相对索引

2024-03-29 09:51:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一种简单的方法来访问相对于Pandas中给定索引的索引DataFrame。请参见下面的代码,其中a绘制了与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?

输出如下:

^{pr2}$

这对于一般的相对索引来说应该是可能的(而不仅仅是一个方向上的+1)。在


Tags: thetoimportnumpydataframepandasdfas
1条回答
网友
1楼 · 发布于 2024-03-29 09:51:44

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

pandas提供pd.Index.get_loc()方法来检索标签的从零开始的integerindex位置。一旦有了integer位置,就可以获得任何偏移量的标签并相应地选择新行:

indexlabel'2'开始,对于column C中的值7

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

7

row标签'2'相对应的基于整数的index1

^{pr2}$

2添加到基于整数的index位置{}得到{}4

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

4

对应的row15

df['C'][next_index]

15

希望这有帮助。在

相关问题 更多 >