Skip to content
Advertisement

Create list from columns and add column to dataframe python

I have this dataframe:

enter image description here

and I would like to create col_list and add it to the dataframe such that it looks like this:

enter image description here

I have tried this code but it doesn’t work:

import pandas as pd
import numpy as np


d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)
print(df)

b = df[['col1', 'col2']].to_numpy()
df = pd.DataFrame({'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8],'col':[np.c_[b]]})

Advertisement

Answer

Try this

import pandas as pd
import numpy as np

d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

df["col_list"] = df.values.tolist()
df
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement