Skip to content

Commit 34365eb

Browse files
committed
Add to_dataframe() to Record.
1 parent 59b09ba commit 34365eb

File tree

3 files changed

+77746
-114
lines changed

3 files changed

+77746
-114
lines changed

demo.ipynb

Lines changed: 77695 additions & 114 deletions
Large diffs are not rendered by default.

tests/test_record.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import unittest
44

55
import numpy as np
6+
import pandas as pd
67

78
import wfdb
89

@@ -527,6 +528,16 @@ def test_4d(self):
527528

528529
assert np.array_equal(sig_round, sig_target)
529530

531+
def test_to_dataframe(self):
532+
record = wfdb.rdrecord("sample-data/test01_00s")
533+
df = record.to_dataframe()
534+
535+
self.assertEqual(record.sig_name, list(df.columns))
536+
self.assertEqual(len(df), record.sig_len)
537+
self.assertEqual(df.index[0], pd.Timedelta(0))
538+
self.assertEqual(df.index[-1], pd.Timedelta(seconds=1 / record.fs * (record.sig_len - 1)))
539+
assert np.array_equal(record.p_signal, df.values)
540+
530541
def test_header_with_non_utf8(self):
531542
"""
532543
Ignores non-utf8 characters in the header part.

wfdb/io/record.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,46 @@ def _arrange_fields(self, channels, sampfrom, smooth_frames):
886886
# Adjust date and time if necessary
887887
self._adjust_datetime(sampfrom=sampfrom)
888888

889+
def to_dataframe(self) -> pd.DataFrame:
890+
"""
891+
Create a dataframe containing the data from this record.
892+
893+
894+
Returns
895+
-------
896+
A dataframe, with sig_name in the columns. The index is a DatetimeIndex
897+
if both base_date and base_time were set, otherwise a TimedeltaIndex.
898+
"""
899+
if self.base_datetime is not None:
900+
index = pd.date_range(
901+
start=self.base_datetime,
902+
periods=self.sig_len,
903+
freq=pd.Timedelta(seconds=1 / self.fs),
904+
)
905+
else:
906+
index = pd.timedelta_range(
907+
start=pd.Timedelta(0),
908+
periods=self.sig_len,
909+
freq=pd.Timedelta(seconds=1 / self.fs),
910+
)
911+
912+
if self.p_signal is not None:
913+
data = self.p_signal
914+
elif self.d_signal is not None:
915+
data = self.d_signal
916+
elif self.e_p_signal is not None:
917+
data = np.array(self.e_p_signal).T
918+
elif self.e_d_signal is not None:
919+
data = np.array(self.e_d_signal).T
920+
else:
921+
raise ValueError("No signal in record.")
922+
923+
return pd.DataFrame(
924+
data=data,
925+
index=index,
926+
columns=self.sig_name
927+
)
928+
889929

890930
class MultiRecord(BaseRecord, _header.MultiHeaderMixin):
891931
"""

0 commit comments

Comments
 (0)