Search code examples
pythonpandastolist

convert selected columns of a pandas dataframe to list


I have a dataframe with several columns, among which 'value1' and 'value2':

   value1  value2    other
0      13       8    xxxxx
1      14       7    xxxxx
2      17       7    xxxxx
3      18       7    xxxxx
4      19       8    xxxxx

Currently I manually have to edit my_list values which are pairs of values into the format below.

my_list = [[13,8],[14,7],[17,7],[18,7],[19,8]]

however I have been able to get the datainto a pandas dataframe in two columns called value1 and and value2 , so for example on my first row in pandas value1 = 13 and value2 = 8 etc.

Is there a way I can write something like tolist() that would output a list of the values in the above structure?


Solution

  • short answer

    Use the tolist method of the underlying numpy array: df.values.tolist()

    or df[['value1', 'value2']].values.tolist() to select only some columns

    details

    You can convert from list to DataFrame and conversely:

    import pandas as pd
    
    my_list = [[13,8],[14,7],[17,7],[18,7],[19,8]]
    
    # list to dataframe
    df = pd.DataFrame(my_list, columns=['value1', 'value2'])
    
    # dataframe to list
    my_list = df.values.tolist()
    

    my_list:

    [[13,8],[14,7],[17,7],[18,7],[19,8]]
    

    df:

       value1  value2
    0      13       8
    1      14       7
    2      17       7
    3      18       7
    4      19       8
    

    how to convert only some columns to list:

    df[['value1', 'value2']].values.tolist()