python - Pandas - 选择给定距离的多行

标签 python pandas jupyter

所以我有一个 pandas 数据框,看起来像这样:

2016-01-28 00:00:00   int   int   int   int   int
2016-01-28 01:00:00   int   int   int   int   int
2016-01-28 02:00:00   int   int   int   int   int

第一列是我的索引列。它有超过 500 行仅供引用。所以,我需要得到:

  • 索引为2016-04-04 00:00:00的行
  • 该行之前的行
  • 该行之前的第二行,
  • 具有所述索引的行之前的第 24 行

我怎样才能做到这一点?

最佳答案

为了解决这个问题,我首先生成一个测试数据集:

import numpy as np

# Generating a fake dataset
date_index = pd.date_range('2016-01-28' ,'2018-01-28', freq='h')
random_data = np.random.rand(date_index.shape[0], 5)
df = pd.DataFrame(random_data, date_index, columns=['A','B','C','D','E'])

print(df.head(4).to_string())
#                            A         B         C         D         E
#2016-01-28 00:00:00  0.904552  0.962807  0.349137  0.490480  0.706348
#2016-01-28 01:00:00  0.150306  0.027296  0.810233  0.318828  0.756861
#2016-01-28 02:00:00  0.024970  0.138997  0.403566  0.759649  0.619711
#2016-01-28 03:00:00  0.048545  0.581297  0.395148  0.398693  0.013036

这样,我们就可以直接使用 loc 访问值:

# Accessing 2016-04-04 00:00:00
df.loc['2016-04-04 00:00:00']
#A    0.202226
#B    0.921532
#C    0.530494
#D    0.177240
#E    0.324215

有多种方法可以获取请求的行。其中之一是:

# Accessing positional index of 2016-04-04 00:00:00
d_current = df.index.get_loc('2016-04-04 00:00:00') # = 1608

# Accessing all the requested rows using `iloc`
d_prev = d_current - 1
d_prev_2 = d_current - 21
d_24h_before = d_current - 24 

df.iloc[d_current]
#A    0.202226
#B    0.921532
#C    0.530494
#D    0.177240
#E    0.324215

df.iloc[d_24h_before]
#A    0.458015
#B    0.572196
#C    0.416302
#D    0.445843
#E    0.130110

关于python - Pandas - 选择给定距离的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59863047/

相关文章:

python - 按 pandas 中的索引列表搜索

python-3.x - 生成生成我观察到的数据帧的代码(多级索引)

python - JupyterLab 中的 pdb 未进入交互模式

python - 生成用户/项目交互

c# - 如何更改菜单的文本颜色?

python - 将对象类型的数据框列转换为浮点型

python - 如何在 Pandas 重新采样中包含字符串

widget - 使用 jupyter 笔记本中的 Bokeh 小部件更新 Bokeh 图

python - 在 swagger python 服务器 stub 处将 token 授权装饰器添加到端点的任何解决方法

python - UnicodeEncodeError : 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)