python - Pandas Dataframe 相对索引

标签 python pandas indexing dataframe

我想要一种简单的方法来访问与 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/

相关文章:

python - 如何根据相似度函数合并两个 pandas DataFrame?

python - 如何以网格格式打印列表列表?

python - OpenCV 描述符移除关键点

python - 如何通过 2x2 平均内核对 Pandas 数据帧进行下采样

Mysql::Error: 指定的键太长;最大 key 长度为 1000 字节

python - 如果需要,使用 SQL 或代码从多个 (4) 表连接中获取结果(python)

python - 如何使用 Pandas 从文件中提取 html 表格?

python - 如何从 "remembering"旧值停止 Dataframe 子集

python - 将列表转换为列表python中的随机列表

MYSQL: Two fields as PRIMARY KEYs + 1 Field as UNIQUE, 一道题