2016-07-15 30 views
2

Ich habe ein Datenframe (df), wo Spalte A Arzneimitteleinheiten ist, die zum Zeitpunkt von Timestamp dosiert wird. Ich möchte die fehlenden Werte (NaN) mit der Wirkstoffkonzentration bei Halbwertszeit des Medikaments (180 Minuten) füllen. Ich kämpfe mit dem Code in Pandas. Würde wirklich Hilfe und Einsicht schätzen. Vielen Dank im VorausWie fillna/fehlende Werte für eine irreguläre Zeitreihe für ein Medikament, wenn Halbwertszeit bekannt ist

df 
         A  
Timestamp              
1991-04-21 09:09:00 9.0   
1991-04-21 3:00:00 NaN  
1991-04-21 9:00:00 NaN  
1991-04-22 07:35:00 10.0  
1991-04-22 13:40:00 NaN   
1991-04-22 16:56:00 NaN  

Angesichts der Halbwertszeit des Medikaments ist 180 Minuten. Ich wollte (Werte) als Funktion der Zeit fillna verstrichen und die Halbwertszeit des Medikaments

so etwas wie

Timestamp    A  

1991-04-21 09:00:00 9.0 
1991-04-21 3:00:00 ~2.25 
1991-04-21 9:00:00 ~0.55 
1991-04-22 07:35:00 10.0 
1991-04-22 13:40:00 ~2.5 
1991-04-22 16:56:00 ~0.75 

Antwort

2

Ihre Zeitstempel sind nicht sortiert und ich gehe davon aus das ein Tippfehler war. Ich habe es unten behoben.

import pandas as pd 
import numpy as np 
from StringIO import StringIO 

text = """TimeStamp     A  
1991-04-21 09:09:00 9.0   
1991-04-21 13:00:00 NaN  
1991-04-21 19:00:00 NaN  
1991-04-22 07:35:00 10.0  
1991-04-22 13:40:00 NaN   
1991-04-22 16:56:00 NaN """ 

df = pd.read_csv(StringIO(text), sep='\s{2,}', engine='python', parse_dates=[0]) 

Dies ist der magische Code.

# half-life of 180 minutes is 10,800 seconds 
# we need to calculate lamda (intentionally mis-spelled) 
lamda = 10800/np.log(2) 

# returns time difference for each element 
# relative to first element 
def time_diff(x): 
    return x - x.iloc[0] 

# create partition of non-nulls with subsequent nulls 
partition = df.A.notnull().cumsum() 

# calculate time differences in seconds for each 
# element relative to most recent non-null observation 
# use .dt accessor and method .total_seconds() 
tdiffs = df.TimeStamp.groupby(partition).apply(time_diff).dt.total_seconds() 

# apply exponential decay 
decay = np.exp(-tdiffs/lamda) 

# finally, forward fill the observations and multiply by decay 
decay * df.A.ffill() 

0  9.000000 
1  3.697606 
2  0.924402 
3 10.000000 
4  2.452325 
5  1.152895 
dtype: float64 
+0

DANK U so viel. Das war perfekt! – Pearl

+0

@Pearl froh, ich könnte helfen. – piRSquared