【问题标题】:Identify time point in DataFrame based on condition per time series根据每个时间序列的条件识别 DataFrame 中的时间点
【发布时间】:2023-03-12 07:26:01
【问题描述】:

我有一个包含时间序列数据的 DataFrame,如下所示:

(TP = 时间点)

gene number   TP1   TP2   TP3   TP4   TP5   TP6
gene1         0.4   0.2   0.1   0.5   0.8   1.9
gene2         0.3   0.05  0.5   0.8   1.0   1.7
....

对于每一行(基因),我想识别其值达到比时间序列中的最小值大 4 倍的水平的 TP,附加条件是这个识别的 TP 必须在最小 TP 之后.因此,对于基因 2,我对 TP3 感兴趣,而不是 TP1(比 TP2 的最小值大 4 倍),因为 TP1 在系列中比最小值 TP2 更早。

所以我尝试构建的脚本的结果是这样的:

gene1    TP4
gene2    TP3
...

我的数据在一个 numpy 数组中。

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    您可以先创建一个掩码ma,然后将最小值之前的所有行值设置为False。接下来,使用此掩码查找每行中的值最小值达到最小值的 4 倍(由True 表示):

    >>> ma = df.values.argmin(axis=1)[:,None] <= np.arange(df.shape[1])
    >>> df.ge(4*df.min(axis=1), axis=0) & ma
             TP1    TP2    TP3   TP4   TP5   TP6
    gene1  False  False  False  True  True  True
    gene2  False  False   True  True  True  True
    

    然后,您可以使用 idxmax 从此布尔数据帧(我将其称为 df1)中检索第一个 True 值的标签:

    >>> df1.idxmax(axis=1)
    gene1    TP4
    gene2    TP3
    dtype: object
    

    【讨论】:

    • 我如何将它应用到数据框的特定切片上,例如我想为每一行运行脚本,但只使用第 6 到 12 列?
    • 您可以使用df.iloc[:, 6:12] 获取DataFrame 的一部分(iloc 按索引号选择,包括端点)。
    • 或者,您可以按标签选择列,例如df[['TP6', 'TP7', ...]]
    • 似乎当一行没有达到4次值时,脚本返回第一列。这本身并不是一个大问题,但只是检查我是否做对了。其次,如何将参数更改为“大于零的值”而不是“最小值的 4 倍”?
    • 这似乎是正确的,是的 - 当未达到 4 倍值时,整行为 False(即零),因此所有值都是最大值并返回第一列。我忽略了这一点,但正如你所说,解决这个问题应该相当简单。
    【解决方案2】:

    这是一种方法:

    df =pd.DataFrame({'TP1':[.4,.3],'TP2':[.2,.05],'TP3':[.1,.5],'TP4':[.5,.8],'TP5':[.8,1.0], 'TP6':[1.9,1.7]},index= ['gene1','gene2'])
    
    def f(x):
        #get min value and index
        min_ind = [ e for e in enumerate(x) if e[1] == x.min()]
        #return only the first value that is greater than the index of the min value and > min value *4
        r =df.columns[[e[0] for e in enumerate(x) if e[1] if e[1] > min_ind[0][1]*4 and e[0]> min_ind[0][0]][0]]
        return r
    

    返回:

    df.apply(f, axis=1)
    
    gene1    TP4
    gene2    TP3
    dtype: object
    

    【讨论】:

    • 这适用于示例,但是在我的数据(格式较大(92rowsx42columns))上运行它时,我收到此错误:IndexError: ('index out of bounds', u'occurred at index 305107')305107 是表中的第一个索引
    猜你喜欢
    • 2018-12-05
    • 2021-06-25
    • 2019-05-11
    • 2012-07-29
    • 2012-11-23
    • 2022-07-19
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多