Search code examples
pythonlistdataframerowmultiple-columns

How to convert a column value to list in Python


I need to convert the value in the column 'value' to a list format. The dataframe df:

    emp_no  value
0   390     10.0
1   395     20.0
2   397     30.0
3   522     40.0
4   525     40.0

Output should be:

    emp_no  value
0   390     [5,10.0]
1   395     [5,20.0]
2   397     [5,30.0]
3   522     [5,40.0]
4   525     [5,40.0]

Solution

  • You could try with map, as well :

    import pandas as pd
    
    df = pd.DataFrame({'em_pno':[390,396,397], 'value':[10.0,6.0,7.0]})
    df['value'] = df['value'].map(lambda x:[5, x])
    
    # IN
       em_pno  value
    0     390   10.0
    1     396    6.0
    2     397    7.0
    # OUT
       em_pno      value
    0     390  [5, 10.0]
    1     396   [5, 6.0]
    2     397   [5, 7.0]