【问题标题】:How to select range in Pandas using a row如何使用行在 Pandas 中选择范围
【发布时间】:2014-09-06 00:49:58
【问题描述】:

我有一个 Pandas 数据框。

我在另一个进程中从该数据框中选择了一行。

在另一种方法中,我现在需要从该行所在的数据框中选择一个范围,然后返回 55 行(如果有这么多的话)。

这是一些伪代码,希望对你有帮助:

df = DataFrame from csv

row = df[3454]

index = row.index
start = max(0, index - 55)
end = max(1, index)
dfRange = df[start:end]

【问题讨论】:

  • 您的代码不起作用吗?你最好使用iloc 语法,因为你所做的只有在这些索引值存在时才有效
  • 如果你还没有读过docs

标签: python pandas


【解决方案1】:

应该这样做

integer_location = np.where(df.index == 3454)[0][0]
start = max(0, integer_location - 55)
end = max(1, integer_location)
dfRange = df.iloc[start:end]

此链接有更多信息 Getting the integer index of a Pandas DataFrame row fulfilling a condition?

【讨论】:

  • 但是 iloc 实际上并没有在数据帧 index 上运行——它在行索引上运行,这可能不一样——即使你有一个整数 index,一旦你开始切片您的数据框,它可能不连续或从 0 开始。我想如果我想要两个 index 值之间的行范围,我可以尝试先找出行索引然后应用此方法?像...df_reindexed = df.reset_index(); start = df_reindexed[df_reindexed['index'] == start].index[0]; end = <similar>; df_reindexed.iloc[start:end]?
猜你喜欢
  • 2018-09-27
  • 2018-08-18
  • 2020-10-06
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
相关资源
最近更新 更多