Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign list value in a pandas df column?

I would like to create a new df column to hold list values.

def add_list_values(row): # row parameter is needed but not in this sample code
    list_val = [1, 'OKOKOK', 2123]
    return list_val

df['new_col'] = df.apply(add_list_values, axis=1)

Error: ValueError: Shape of passed values is (91, 4), indices imply (91, 2)

When I test by simply assigning a column with list value, I got similar error.

df['new_col2'] = [1, 'OKOKOK', 2123]

ValueError: Length of values does not match length of index
like image 936
KubiK888 Avatar asked Sep 12 '25 16:09

KubiK888


1 Answers

If I understand correctly, try this instead of the line that gives you an error:

df['c']=[[1, 'OKOKOK', 2123]]*len(df)
df
Out[148]: 
   a  b                  c
0  1  1  [1, OKOKOK, 2123]
1  3  4  [1, OKOKOK, 2123]
2  3  4  [1, OKOKOK, 2123]
like image 188
BENY Avatar answered Sep 14 '25 22:09

BENY