【问题标题】:Python Pandas : select a range of indexPython Pandas:选择一个索引范围
【发布时间】:2017-01-19 17:00:58
【问题描述】:
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],但我不知道怎么做。

【问题讨论】:

    标签: python pandas indexing dataframe


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      另一种选择是在提取值之前将LogRatio 列移动n

      n = 2
      df.LogRatio.shift(-n)[df.Sample == "CD0695"]
      
      #3    1.91
      #Name: LogRatio, dtype: float64
      

      【讨论】:

        猜你喜欢
        • 2019-02-08
        • 2015-09-15
        • 2021-05-24
        • 2023-03-11
        • 2017-11-20
        • 2018-02-07
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        相关资源
        最近更新 更多