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