Search code examples
pythonlistmatrixpython-itertools

How to transfer this list to a 3xN matrix? Python


my_list = ["TITLE","COMPANY","TENURE",
"Board Member","Softbank Corp","06/2007–06/2015",
 "Chairman","Alibaba.Com Ltd","10/2007–PRESENT",
"Board Member","Huayi Brothers","FORMER"]

I have the above list and I want to transfer it to a 3xN format (3 columns, N rows)

Expected outputs:

TITLE           COMPANY        TENURE
Board Member  Softbank Corp  06/2007–06/2015
Chairman     Alibaba.Com Ltd 10/2007–PRESENT
Board Member  Huayi Brothers  FORMER

Thanks in advance for your help!


Solution

  • U can use pandas dataframe:

    The DataFrame can be created using a single list or a list of lists.

    import pandas as pd
    
    my_list = ["TITLE","COMPANY","TENURE",
    "Board Member","Softbank Corp","06/2007–06/2015",
     "Chairman","Alibaba.Com Ltd","10/2007–PRESENT",
    "Board Member","Huayi Brothers","FORMER"]
    
    # Convert flat list into nested list with 3 items
    data_ = [my_list[i:i + 3] for i in range(0,len(my_list),3)] 
    
    #Create a DataFrame from Lists 
    print (pd.DataFrame(data_[1:],columns=data_[0:1][0]))
    

    output:

              TITLE          COMPANY           TENURE
    0  Board Member    Softbank Corp  06/2007–06/2015
    1      Chairman  Alibaba.Com Ltd  10/2007–PRESENT
    2  Board Member   Huayi Brothers           FORMER