根据每个时间序列的条件确定数据帧中的时间点

2024-10-01 07:12:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

(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数组中。你知道吗


Tags: 数据number基因时间序列genetptp3
2条回答

您可以首先创建一个掩码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

这里有一个方法:

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

相关问题 更多 >