Search code examples
python-3.xpandasdataframetranspose

Transpose columns pandas dataframe


I have a DF like this:

ID Name Mail Phone1 Phone2 Mail1 Mail2 contact phone contact mail
70 DASS ARGENTINA SRL [email protected] 2664941642 2664941644 [email protected] [email protected] 115456789 [email protected]
71 PEPSI [email protected] 0456535365 7766554399 [email protected] [email protected] 8864545332 [email protected]
ID Name LOCATOR
70 DASS ARGENTINA SRL [email protected]
70 DASS ARGENTINA SRL 2664941642
70 DASS ARGENTINA SRL 2664941644
70 DASS ARGENTINA SRL [email protected]
70 DASS ARGENTINA SRL [email protected]
70 DASS ARGENTINA SRL 115456789
70 DASS ARGENTINA SRL [email protected]
71 PEPSI [email protected]
71 PEPSI 0456535365
71 PEPSI 7766554399
71 PEPSI [email protected]
71 PEPSI [email protected]
71 PEPSI 8864545332
71 PEPSI [email protected]

Is it possible to do anythong like this? I´ve tried with transpose function but I´m not getting the output like the example above


Solution

  • use pd.melt to flatten the dataframe and then sort and remove the unwanted columns

    df.drop(columns='ID').melt(id_vars='Name', value_name='Locator').sort_values('Name').drop(columns='variable')
    
                      Name  Locator
    0   DASS ARGENTINA SRL  [email protected]
    2   DASS ARGENTINA SRL  2664941642
    4   DASS ARGENTINA SRL  2664941644
    6   DASS ARGENTINA SRL  [email protected]
    8   DASS ARGENTINA SRL  [email protected]
    10  DASS ARGENTINA SRL  115456789
    12  DASS ARGENTINA SRL  [email protected]
    1   PEPSI               [email protected]
    3   PEPSI               456535365
    5   PEPSI               7766554399
    7   PEPSI               [email protected]
    9   PEPSI               [email protected]
    11  PEPSI               8864545332
    13  PEPSI               [email protected]