import numpy as np
from IPython.display import display, HTML
Recreating the DataFrame class
class DataFrameCopy:
def __init__(self, data: dict):
self.data = data
self.create_index() # Run method to create index on initializing of object
# Add index to dataset
def create_index(self):
= {}
df = 0
max_rows
for key, value in self.data.items(): # return max number of rows to propagate index
if len(value) > max_rows:
= len(value)
max_rows
= list(range(0, max_rows)) # Create index column
index_length 'index'] = index_length # Add index to temp dict
df[self.data) # Add initialize data to temp dict and reassign data that includes index
df.update(self.data = df
# Replicating the head function of pandas
def head(self, rows: int):
= '<table style="border-collapse: collapse; font-family: Arial; font-size: 14px;">'
table
# loop to insert columns
+= '<tr>'
table for key in self.data.keys():
+= f'<th>{key}</th>'
table += '</tr>'
table
# Below is the loop to insert rows values for each column
= 0 # i is used to keep track of the row level, whereby
i while True:
for key, value in self.data.items():
+= f"<td>{value[i]}</td>"
table += "</tr>"
table += 1
i
# When desired amount of rows have been inserted in html, break loop
if i == rows:
break
+= "</table>"
table
# Read string as html
= HTML(table)
chart
return display(chart)
Initializing DataFrameCopy class with data in the form of dictionary just like in pandas
= {'Col 1': [1, 2, 3, 4, 5], 'Col 2': [6, 7, 8, 9, 10]}
data = DataFrameCopy(data) df
Below the data from the object is called where we can see that the index has been automatically created
df.data
{'index': [0, 1, 2, 3, 4], 'Col 1': [1, 2, 3, 4, 5], 'Col 2': [6, 7, 8, 9, 10]}
Using the head method for the class works simply like the pandas version, where we can choose the amount of rows we would like to show. The method then displays a html table of the data for improved readability.
4) df.head(
index | Col 1 | Col 2 |
---|---|---|
0 | 1 | 6 |
1 | 2 | 7 |
2 | 3 | 8 |
3 | 4 | 9 |