python - 仅从数据框中获取前三个值

标签 python python-3.x pandas numpy

我是 python 和 pandas 的新手。在这里,我有一个数据框,就像,

     Id     Offset       feature
   0        0              2
   0        5              2
   0        11             0
   0        21             22
   0        28             22
   1        32              0
   1        38             21
   1       42             21
   1        52             21
   1        55              0
   1        58              0
   1        62              1
   1        66              1
   1        70              1
   2        73              0
   2        78              1
   2        79              1

由此,我尝试从该列中获取前三个值及其偏移量。

所以,输出会是这样的,

offset  Feature
11        2
21        22
28         22
// Here these three values are `of the 0 which is at 32 offset`

In the same dataframe for next place where is 0 

38        21
42        21 
52        21

58        0
62        1
66        1

有什么办法可以让我得到这个吗? 谢谢 这将基于文档 ID。

最佳答案

即使我对 Pandas 很陌生,但我已经尝试回答你的问题。 我将您的数据填充为 data.csv 中的逗号分隔值,然后使用切片来获取前 3 列。

import pandas as pd

df = pd.read_csv('./data.csv')
for index in (df.loc[df['Feature'] == 0]).index:
    print(df.loc[index-3:index-1])

输出如下所示。最左边的列是索引,如果不需要,可以将其丢弃。这是您要找的吗?

   Offset  Feature
2      11        2
3      21       22
4      28       22
   Offset  Feature
6      38       21
7      42       21
8      52       21
   Offset  Feature
7      42       21
8      52       21
9      55        0
    Offset  Feature
11      62        1
12      66        1
13      70        1

注意:可能有一种更Pythonic的方法来做到这一点。

关于python - 仅从数据框中获取前三个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689880/

相关文章:

python - Pandas 数据框替换列中的子字符串,给出意外的结果

python - PyTorch张量高级索引

python - python中有一个包可以创建每月热图吗?

python - 如何将导入的txt文件的文件名添加到python中的数据帧

python - 在数据 block 上安装新版本后,pandas 版本未更新

python - 将这些对象转换为 python 列中的 int64

python - 不使用点符号间接访问 Python 实例属性

python - 遍历将来的结果时,如何获取发送给ThreadPoolExecutor的参数?

python - 将 Column2 值替换为满足 Column1 条件的字典键

python - Python姿势估计示例错误