Home > Software engineering >  Create list from columns and add column to dataframe python
Create list from columns and add column to dataframe python

Time:09-28

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]]})

CodePudding user response:

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
  • Related