【问题标题】:Pandas Dataframe relative indexingPandas Dataframe 相对索引
【发布时间】:2015-12-26 13:14:50
【问题描述】:

我想要一种简单的方法来访问相对于 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)。

【问题讨论】:

  • Pandas 背后的一个想法是能够轻松地对数据执行批量操作并避免迭代。您能否详细说明您要在更高级别上实现的目标?
  • 为什么不直接使用基于整数的索引,即iloc[2, 2]
  • 在最高级别,这是一个四分五裂的游戏(连续 5 个)。我决定将电路板放在 DataFrame 中(主要是因为我是 python 新手)。我的 AI 对手现在可以通过寻找连续的 X 链来发现潜在威胁。假设一连串的三个 X 在 F5、F6、F7 处。我的约定是链的地址为 F7,长度为 3。如果 AI 想要放一个 O 来阻止链,它必​​须转到地址 F7 并将数字索引迭代 1 以到达 F8。跨度>
  • 很高兴听到我这样做很愚蠢。

标签: python pandas indexing dataframe


【解决方案1】:

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

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

index label '2' 开始,价值7 in column C

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

7

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

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

对应的row15

df['C'][next_index]

15

希望这会有所帮助。

【讨论】:

  • 如果我的标签不是整数怎么办?也许我错过了 DataFrame 应该为我做什么。如果我有一个索引在日历日期中的 DataFrame,并且我想访问 1991 年 7 月 23 日到之后 100 天之间的所有内容(不必知道 100 天后的日期)怎么办?
  • 我使用了string 标签来说明如何在基于labelindex 的选择之间来回切换;你也可以使用datetime。但是,您的问题是关于一个具体的例子。对于您随后介绍的游戏示例,您最好在幕后使用基于integer 的索引,相应地翻译字段名称以方便算术。另请查看文档:pandas.pydata.org/pandas-docs/stable/indexing.html
猜你喜欢
  • 2016-01-18
  • 2017-06-11
  • 2019-04-13
  • 2018-06-18
  • 2018-12-24
  • 2016-02-18
  • 1970-01-01
  • 2013-11-19
  • 2022-01-10
相关资源
最近更新 更多