Python Forum
Converting Pandas DataFrame to a table of hourly blocks
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting Pandas DataFrame to a table of hourly blocks
#1
Photo 
Hello everyone,

I have a data frame that I'd like to visualize as a table (see attached file). Is that possible with pandas? Your help will be very much appreciated.


import pandas as pd
import numpy as np

df = pd.DataFrame({'courseid':['CHEM1250', 'CHEM1250', 'CHEM1250', 'PHYS1200', 'PHYS1200', 'BIOL1150', 'BIOL1150'], \
                   'coursesec':['L01', 'L02', 'L03', 'L01','L02','L01','L01'], \
                   'Day':['Monday','Tuesday','Friday','Tuesday','Thursday','Wednesday','Wednesday'], \
                   'starttime':['8:00', '12:00', '13:00', '9:00', '11:00', '8:00', '13:00'], \
                   'endtime':['9:30', '12:30', '14:00', '10:30','12:00', '9:30', '14:30'], \
                   'instructorid':['John', 'John', 'Bob', 'Jenna', 'Michel', 'Michel', 'Alice']})

print(df)

Attached Files

Thumbnail(s)
   
Reply
#2
Can do it like this,it's a little tricky to get CSS placement right.
Generate a schedule.html
import pandas as pd

df = pd.DataFrame({
    'courseid':    ['CHEM1250', 'CHEM1250', 'CHEM1250',
                    'PHYS1200', 'PHYS1200',
                    'BIOL1150', 'BIOL1150'],
    'coursesec':   ['L01', 'L02', 'L03',
                    'L01', 'L02',
                    'L01', 'L01'],
    'Day':         ['Monday', 'Tuesday', 'Friday',
                    'Tuesday', 'Thursday',
                    'Wednesday', 'Wednesday'],
    'starttime':   ['8:00', '12:00', '13:00',
                    '9:00', '11:00',
                    '8:00', '13:00'],
    'endtime':     ['9:30', '12:30', '14:00',
                    '10:30', '12:00',
                    '9:30', '14:30'],
    'instructorid':['John', 'John', 'Bob',
                    'Jenna', 'Michel',
                    'Michel', 'Alice']
})

# Create blank grid: index = 08:00–22:00 in 30-min steps, columns = Monday–Friday
times = pd.date_range("08:00", "22:00", freq="30min").time
time_slots = [t.strftime("%H:%M") for t in times]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
grid = pd.DataFrame("", index=time_slots, columns=days)

# Fill each time slot with the course info
for _, row in df.iterrows():
    slots = pd.date_range(row.starttime, row.endtime, freq="30min").time
    # drop the end slot so that 9:30–10:00 goes into the 9:30 row, etc.
    slots = [t.strftime("%H:%M") for t in slots[:-1]]
    text = f"{row.courseid} {row.coursesec}<br>Instructor: {row.instructorid}"
    grid.loc[slots, row.Day] = text

# Turn the time‐index into a real column named "Time" and hide the integer index
grid = grid.rename_axis("Time").reset_index()
def bg_color(val):
    if "CHEM" in val:
        return "background-color: #d1ecf1;"
    if "PHYS" in val:
        return "background-color: #f8d7da;"
    if "BIOL" in val:
        return "background-color: #fff3cd;"
    return ""

# Define table & cell border styles
table_styles = [
    {"selector":"table", "props": [("border-collapse", "collapse"), ("width", "100%")]},
    {"selector":"th, td", "props": [("border", "1px solid #ccc"), ("padding", "6px"), ("vertical-align", "top")]},
    {"selector":"th", "props": [("background-color", "#fafafa"), ("font-weight", "bold")]},
]

# Build the Styler
styler = (
    grid.style
        .map(bg_color)
        .set_table_styles(table_styles)
        .set_caption("Weekly Schedule")
        .hide(axis="index")
)

# Export to HTML
html = styler.to_html(escape=False)
with open("schedule.html", "w", encoding="utf-8") as f:
    f.write(html)

print("✅ schedule.html generated")
[Image: wmPysP.png]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Most efficient way to roll through a pandas dataframe? sawtooth500 2 1,264 Aug-28-2024, 10:08 AM
Last Post: Alice12
  docx file to pandas dataframe/excel iitip92 1 3,095 Jun-27-2024, 05:28 AM
Last Post: Pedroski55
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 1,475 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  RSA Cipher with blocks Paragoon2 0 1,263 Nov-26-2023, 04:35 PM
Last Post: Paragoon2
  Trying to get counts/sum/percentages from pandas similar to pivot table cubangt 6 3,610 Oct-06-2023, 04:32 PM
Last Post: cubangt
  Using pyodbc&pandas to load a Table data to df tester_V 3 3,172 Sep-09-2023, 08:55 PM
Last Post: tester_V
  Question on pandas.dataframe merging two colums shomikc 4 2,111 Jun-29-2023, 11:30 AM
Last Post: snippsat
  Pandas AttributeError: 'DataFrame' object has no attribute 'concat' Sameer33 5 10,803 Feb-17-2023, 06:01 PM
Last Post: Sameer33
  Converting a json file to a dataframe with rows and columns eyavuz21 13 15,109 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  help how to get size of pandas dataframe into MB\GB mg24 1 5,699 Jan-28-2023, 01:23 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020