Python Pandas:选择索引范围

3
datas = [['RAC1','CD0287',1.52], ['RAC1','CD0695',2.08], ['RAC1','ADN103-1',2.01], ['RAC3','CD0258',1.91], ['RAC3','ADN103-3',1.66], ['RAC8','CD0558',1.32], ['RAC8','ADN103-8',2.89]]
labels = ['Plate', 'Sample', 'LogRatio']
df = pd.DataFrame(data = datas, columns=labels, index=[8, 3, 5, 4, 12, 44, 2])

   Plate    Sample  LogRatio
8   RAC1    CD0287      1.52
3   RAC1    CD0695      2.08
5   RAC1  ADN103-1      2.01
4   RAC3    CD0258      1.91
12  RAC3  ADN103-3      1.66
44  RAC8    CD0558      1.32
2   RAC8  ADN103-8      2.89

我想通过索引找到“CD0695”样本之后n行的样本的logratio值。

n = 2
indexCD0695 = df[df['Sample']=="CD0695"].index.tolist()
print(indexCD0695)
> [3] 
logratio_value = df.iloc[indexCD0695[0]+n]['LogRatio']
> 1.32 #NOT THE RESULT I WOULD LIKE 

我不知道如何获得单个索引而不是列表,因此我只取列表的第一个元素indexCD0695 [0],这不是我的主要问题。 我的真正问题是,我获得了位置为3 + 2的索引位置的值,而我希望从CD0695的位置开始获得索引(我可以通过df.loc获得),并在此起始索引后找到第二行:

4   RAC3    CD0258      1.91

所以logratio值为1.91

我认为我需要混合df.loc[indexCD0695]df.iloc[n],但我不知道如何操作。

2个回答

4

使用get_loc方法通过索引标签获取特定行的序数位置,然后可以使用iloc方法获取该行之后的第n行:

In [261]:
indexCD0695 = df.index.get_loc(df[df['Sample']=="CD0695"].index[0])
indexCD0695

Out[261]:
1

In [262]:
n=2
logratio_value = df.iloc[indexCD0695+n]['LogRatio']
logratio_value

Out[262]:
1.9099999999999999

1

另一个选项是在提取值之前将您的LogRatio列向n移动:

n = 2
df.LogRatio.shift(-n)[df.Sample == "CD0695"]

#3    1.91
#Name: LogRatio, dtype: float64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接