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

我是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

据此,我试图从列中获取前三个值以及其偏移量。

SO,输出将是

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。

WOJIAXIAOMIAN3 回答:仅从数据框中获取前三个值

即使我对熊猫还很陌生,但我试图回答您的问题。 我在data.csv中将数据填充为逗号分隔的值,然后使用切片得到前三列。

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方式。

,

您可以使用 loc 在列中获取当前 0 值的前3行。

关注代码:

import pandas as pd
df = pd.read_csv("<path_of_the_file">)
zero_indexes = list(df[df['Feature'] == 0].index)
for each_zero_index in zero_indexes:
    df1 = df.loc[each_zero_index - 3: each_zero_index]
    print(df1) # This dataframe has 4 records. Your previous three including the zero record.

输出:

   Offset  Feature
2      11        2
3      21       22
4      28       22
5      32        0
   Offset  Feature
6      38       21
7      42       21
8      52       21
9      55        0
    Offset  Feature
7       42       21
8       52       21
9       55        0
10      58        0
    Offset  Feature
11      62        1
12      66        1
13      70        1
14      73        0
本文链接:https://www.f2er.com/3168109.html

大家都在问