Search code examples
python-3.xpandasdataframetransposemelt

Transpose few columns and reshaping them


I am looking to transpose only certain columns in my dataframe and their values by keeping certain columns fixed.

WO.No           LineSubType      ProductName  Desc  Problem
WO-00201182     P-A-T                        
WO-00201182     Parts           18112135     FLOW  Liquid
WO-00201182     Parts           18112200    ArmF9  Liquid

Result Table

WO.No           LineSubType     ProductName+Desc1 ProductName+Desc2  Problem
WO-00201182     P-A-T/Parts     18112135 + FLOW  18112200 + ArmF9   Liquid             

enter image description here


Solution

    • have used approach of self join
    • clearly sub-type columns could be merged into one if required
    df = pd.read_csv(io.StringIO("""WO.No           LineSubType  LineNumber    ProductName  Desc  Problem
    WO-00201182     P-A-T        WL-01014402                
    WO-00201182     Parts        WL-01014744   18112135     FLOW  Liquid"""), sep="\s+")
    
    
    df = (
        df.loc[df["LineSubType"].eq("P-A-T")]
        .drop(columns=["ProductName", "Desc", "Problem"])
        .merge(
            df.loc[df["LineSubType"].eq("Parts")],
            on="WO.No",
            suffixes=(" .P.A.T.", " Parts"),
        )
    )
    
    df
    
    
    WO.No LineSubType .P.A.T. LineNumber .P.A.T. LineSubType Parts LineNumber Parts ProductName Desc Problem
    0 WO-00201182 P-A-T WL-01014402 Parts WL-01014744 1.81121e+07 FLOW Liquid