-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLogged_DataFrame.py
More file actions
51 lines (43 loc) · 1.71 KB
/
Logged_DataFrame.py
File metadata and controls
51 lines (43 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pandas as pd
from datetime import datetime
class LoggedDF(pd.DataFrame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.created_at = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
custom_data = {"A": [10, 20], "B": [30, 40]}
custom_df = LoggedDF(custom_data)
print(custom_df.values)
print(custom_df.created_at)
# Recap: create DataFrames from a dictionary of lists - construct the df column by column
dict_of_list = {"col_1": [val_11, val_12], "col_2": [val_21, val_22]}
my_df = pd.DataFrame(list_of_dict)
print(my_df)
# Turn created_at into a read-only attribute using @property
class LoggedDF2(pd.DataFrame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._created_at = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
@property
def created_at(self):
return self._created_at
custom_data = {"A": [10, 20], "B": [30, 40]}
custom_df = LoggedDF2(custom_data)
print(custom_df.created_at)
custom_df.created_at = '2023 Nov 01'
# AttributeError: property 'created_at' of 'LoggedDF2' object has no setter
# Turn created_at into a read-write attribute using @property and @xxx.setter
class LoggedDF3(pd.DataFrame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._created_at = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
@property
def created_at(self):
return self._created_at
@created_at.setter
def created_at(self, new_date):
self._created_at = new_date
custom_data = {"A": [10, 20], "B": [30, 40]}
custom_df = LoggedDF3(custom_data)
print(custom_df.created_at)
custom_df.created_at = '2023 Nov 01'
print(custom_df.created_at) # 2023 Nov 01