pythonpandasexceldataframepandas-styles

styling a pandas table and merging 2 dataframes


I wanted to style a pandas table, but I'm not able to reshape it every other row, color it this way or set borders for it. I'd be thankful if anyone helps me with this. I uploaded both tables below. The right side table is my table at the moment and the left one is my target.

Content Based MOVIES TITLE Content Based MOVIES ID Colaborative Filtering MOVIES TITLE Colaborative Filtering MOVIES ID
Ordinary People 1956 Interstate 60 6902
Firewalker 2477 Rubber 81132
Fantastic Planet, The (Planète sauvage, La) 2495 Dragonheart 2: A New Beginning 117646
Airport '77 2522 Inside Out 134853
Mister Roberts 3035 Wizards of Waverly Place: The Movie 148775

enter image description here

To color it, I tried to change tables properties, using style.set_properties and also used different join and merge techniques to stick two tables every other row, though none of'em worked.


Solution

  • You can lreshape your DataFrame, then use apply/applymap_index (which are Excel friendly) :

    out = pd.lreshape(
        df, {
            "TITLE": ["Content Based MOVIES TITLE", "Colaborative Filtering MOVIES TITLE"],
             "ID": ["Content Based MOVIES ID", "Colaborative Filtering MOVIES ID"]
        }
    )
    
    import numpy as np
    
    #rows
    purple = "background-color: #ffff99; color: black"
    yellow = "background-color: #b376e0; color: black"
    border = ["border-right: 3px solid black", ""]
    
    #header
    bgray = [
        "border-right: 3px solid black; background-color: #e9e8fc; color: black",
        "background-color: #e9e8fc; color: black;"
    ]    
    
    (
        out.style
            .apply(lambda x: np.where(x.index % 2, yellow, purple))
            .apply(lambda _: border, axis=1)
            .apply_index(lambda _: bgray, axis=1)
            # .to_excel("output.xlsx", index=False) #optional
    )
    

    Output :

    enter image description here