Skip to content

Commit

Permalink
Add to_dataframe() to Record.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivorforce committed Jun 8, 2022
1 parent 59b09ba commit b97c579
Show file tree
Hide file tree
Showing 3 changed files with 77,746 additions and 114 deletions.
77,809 changes: 77,695 additions & 114 deletions demo.ipynb

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions tests/test_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import unittest

import numpy as np
import pandas as pd

import wfdb

Expand Down Expand Up @@ -527,6 +528,16 @@ def test_4d(self):

assert np.array_equal(sig_round, sig_target)

def test_to_dataframe(self):
record = wfdb.rdrecord("sample-data/test01_00s")
df = record.to_dataframe()

self.assertEqual(record.sig_name, list(df.columns))
self.assertEqual(len(df), record.sig_len)
self.assertEqual(df.index[0], pd.Timedelta())
self.assertEqual(df.index[-1], pd.Timedelta(seconds=1 / record.fs * (record.sig_len - 1)))
assert np.array_equal(record.p_signal, df.values)

def test_header_with_non_utf8(self):
"""
Ignores non-utf8 characters in the header part.
Expand Down
40 changes: 40 additions & 0 deletions wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,46 @@ def _arrange_fields(self, channels, sampfrom, smooth_frames):
# Adjust date and time if necessary
self._adjust_datetime(sampfrom=sampfrom)

def to_dataframe(self) -> pd.DataFrame:
"""
Create a dataframe containing the data from this record.
Returns
-------
A dataframe, with sig_name in the columns. The index is a DatetimeIndex
if both base_date and base_time were set, otherwise a TimedeltaIndex.
"""
if self.base_datetime is not None:
index = pd.date_range(
start=self.base_datetime,
periods=self.sig_len,
freq=pd.Timedelta(seconds=1 / self.fs),
)
else:
index = pd.timedelta_range(
start=pd.Timedelta(0),
periods=self.sig_len,
freq=pd.Timedelta(seconds=1 / self.fs),
)

if self.p_signal is not None:
data = self.p_signal
elif self.d_signal is not None:
data = self.d_signal
elif self.e_p_signal is not None:
data = np.array(self.e_p_signal).T
elif self.e_d_signal is not None:
data = np.array(self.e_d_signal).T
else:
raise ValueError("No signal in record.")

return pd.DataFrame(
data=data,
index=index,
columns=self.sig_name
)


class MultiRecord(BaseRecord, _header.MultiHeaderMixin):
"""
Expand Down

0 comments on commit b97c579

Please sign in to comment.