Skip to content

Instantly share code, notes, and snippets.

View str_repr_override_proper.py
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Student({self.name!r}, {self.age})"
def __str__(self):
return f"Student Name: {self.name}; Age: {self.age}"
View str_repr_override.py
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "Student __repr__ string"
def __str__(self):
return "Student __str__ string"
View str_repr_builtin_classes.py
>>> name = "Danny"
>>> age = 15
>>> student = {"name": name}
>>> scores = [100, 99, 95]
>>> location = ('123 Main', 'NY')
>>> for item in (name, age, student, scores, location):
... print(f"{type(item)!s: <15}| repr: {repr(item): <20}| str: {str(item)}")
...
<class 'str'> | repr: 'Danny' | str: Danny
<class 'int'> | repr: 15 | str: 15
View pandas_data_time.py
>>> data = {"timestamp": ["01/01/2022 09:01:00", "01/02/2022 08:55:44", "05/01/2022 22:01:00"],
... "category": list('ABC')}
>>> df = pd.DataFrame(data)
>>> df.dtypes
timestamp object
category object
dtype: object
>>> df["timestamp"] = pd.to_datetime(df["timestamp"])
>>> df.dtypes
timestamp datetime64[ns]
View pandas_date_range.py
>>> pd.date_range(start="12/01/2022", end="12/07/2022")
DatetimeIndex(['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04',
'2022-12-05', '2022-12-06', '2022-12-07'],
dtype='datetime64[ns]', freq='D')
View pandas_date_index.py
>>> import datetime
>>> start_date = datetime.datetime(2022, 12, 1)
>>> one_week = [start_date + datetime.timedelta(days=x) for x in range(7)]
>>> pd.DatetimeIndex(one_week)
DatetimeIndex(['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04',
'2022-12-05', '2022-12-06', '2022-12-07'],
dtype='datetime64[ns]', freq=None)
View pandas_to_datetime.py
>>> pd.to_datetime("Jan 01, 2022")
Timestamp('2022-01-01 00:00:00')
>>> pd.to_datetime(["01/01/2022", "01/02/2022", "01/03/2022"])
DatetimeIndex(['2022-01-01', '2022-01-02', '2022-01-03'], dtype='datetime64[ns]', freq=None)
>>> pd.to_datetime(pd.Series(["01/01/2022", "01/02/2022", "01/03/2022"]))
0 2022-01-01
1 2022-01-02
2 2022-01-03
dtype: datetime64[ns]
View pandas_date_parsing_custom.py
>>> from datetime import datetime
>>> pd.read_csv("custom_dt_fmt.csv", parse_dates=["date"], date_parser=lambda x: datetime.strptime(x, "%b_%d_%Y"))
date category balance
0 2022-01-01 A 100
1 2022-02-02 B 200
2 2022-03-12 C 300
View pandas_parse_dates_fmt.py
>>> pd.read_csv("custom_dt_fmt.csv", parse_dates=["date"], infer_datetime_format=True)
date category balance
0 Jan_01_2022 A 100
1 Feb_02_2022 B 200
2 Mar_12_2022 C 300
View pandas_parse_dates_cols.py
>>> df_cols = pd.read_csv("dates_text_cols.csv", parse_dates={"date": ["y", "m", "d"]})
>>> df_cols
date category balance
0 2022-01-01 A 100
1 2022-02-02 B 200
2 2022-03-12 C 300