Skip to content
Advertisement

Pandas DataFrame column numerical integration

Currently I have a DataFrame as shown below:

Device   TimeSec  Current  
 1       0.1      0.02
 1       0.25     0.05
 1       0.32     0.07
 1       0.45     0.12
 1       1.32     0.34
 1       2.37     2.24
 2       0.22     0.56
 2       0.34     0.79
 2       1.87     2.76
 2       3.21     3.11
 3       0.16     1.87
 3       1.12     2.33
 3       2.45     3.21
 3       3.45     5.11
 ......

I would like to do the numerical integration of Current with TimeSec (∫Idt) for different Devices and collect the data into a new DataFrame as below:

Device   IntegratedCurrent  
 1         x
 2         y
 3         z
 

The problem is that the time interval is not even and the number of data for each device is not even as well.

Advertisement

Answer

Use some numerical integration function, e.g., scipy.integrate.trapz:

from scipy import integrate

df.groupby(df.Device).apply(lambda g: integrate.trapz(g.Current, x=g.TimeSec))

Note that this function, using the trapezoid integration rule, allows to specify the x values.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement