'How to append row value to the other column

I have a table that includes two columns:

P_SEG SEG_ID
1 [2, 4]
2 [4, 3,5]

I want to create a new column that includes the 1st column value in the second column list as follows,

P_SEG SEG_ID New Column
1 [2, 4] [1, 2, 4]


Solution 1:[1]

You can try apply on rows or add the two columns:

df['New Column'] = df.apply(lambda row: [row['P_SEG']]+row['SEG_ID'], axis=1)

# or

df['New Column'] = df['P_SEG'].apply(lambda x: [x]) + df['SEG_ID']
print(df)

   P_SEG     SEG_ID    New Column
0      1     [2, 4]     [1, 2, 4]
1      2  [4, 3, 5]  [2, 4, 3, 5]

Solution 2:[2]

You can join lists with scalar in list comprehension:

df['New Column'] = [[y, *x] for x, y in zip(df['SEG_ID'], df['P_SEG'])]
print (df)
   P_SEG     SEG_ID    New Column
0      1     [2, 4]     [1, 2, 4]
1      2  [4, 3, 5]  [2, 4, 3, 5]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ynjxsjmh
Solution 2 jezrael